← Microsoft bank

Microsoft · Question 49 · Binary Search

Search in Rotated Sorted Array

Binary SearchJavacode⏱ O(logn)💾 O(1)
Product-based

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. 1Identify the sorted half via nums[left] vs nums[mid].
  2. 2Narrow 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

Time O(logn)Space O(1)Loops 2Branches 4Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intsearch(int[] nums, inttarget)DEFINE left = 0, right =nums.length - 1while (left <= right)DEFINE mid = left + (right- left) / 2if (nums[mid] ==target) return midif (nums[left] <=nums[mid])if (nums[left] <=target && target <nums[mid]) right = mi…ELSE} elseRETURN -1DEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.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
1/20

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits