Home › Company-wise questions › Microsoft › Search in Rotated Sorted Array ← Microsoft bank
Microsoft · Question 49 · Binary Search
Search in Rotated Sorted Array Binary Search Java code ⏱ O(logn) 💾 O(1)
Product-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
Problem Given a rotated sorted array, search for a target value.
Approach Find the sorted half each round and narrow into it.
Time O(logn)Space O(1)
How it works 1 Identify the sorted half via nums[left] vs nums[mid]. 2 Narrow into the half that can hold the target. Sample input / output Input:
7
4 5 6 7 0 1 2
0
Output:
4 Constraints 1 <= n <= 5000; distinct values.
Solution — read it, then walk it Flowchart Pseudocode
Time O(logn)Space O(1)Loops 2Branches 4Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
yes no ↻ repeat START import java.util.* DEFINE class Main DEFINE static int search(int[] nums, int target) DEFINE left = 0, right = nums.length - 1 while (left <= right) DEFINE mid = left + (right - left) / 2 if (nums[mid] == target) return mid if (nums[left] <= nums[mid]) if (nums[left] <= target && target < nums[mid]) right = mi… ELSE } else RETURN -1 DEFINE static void main(String[] args) java.util.Scanner sc = new java.util.Scanner(System.in) DEFINE n = sc.nextInt() DEFINE [] nums = new int[n] for (int i = 0; i < nums.length; i++) nums[i] = sc.nextInt() DEFINE target = sc.nextInt() System.out.println(search(nums, target)) END start / end statement condition loop returns definition← Q48 · Find Minimum in Rotated Sorted Array Q50 · Find First and Last Position of Element in Sorted Array → Solution code Core logic highlighted in green
Language Python Javasource C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →