</> MAANG.io
coding interview ยท 101

Foundations

Master coding interviews with comprehensive coverage of data structures, algorithms, and problem-solving techniques. Progress from fundamentals to advanced topics with expertly curated content.

0/255 solved 0% complete

Classic and Rotated

What is this?

This is binary search in its most recognizable form: you have a sorted list, and you want to find a value (or the spot where it would go) by halving the range each step. The twist is "rotated" arrays โ€” a sorted list that someone cut and swapped, like a deck of cards split in the middle, so it reads 4 5 6 7 0 1 2. Even though the whole thing isn't sorted anymore, at every midpoint one of the two halves still is, and that's enough of a clue to keep throwing half the array away.

flowchart TD A["Look at middle element"] --> B["Find the sorted half"] B --> C["Is target inside the sorted half"] C --> D["Yes keep that half"] C --> E["No keep the other half"] D --> A E --> A

๐Ÿ’ก Fun fact: The "spin a sorted array" trick behind rotated search isn't just an interview gimmick โ€” it's how circular buffers and log-rotation systems store data that wraps around the end and continues at the start, so the newest entry can sit anywhere in the array.

๐Ÿ”“ The 5 problems in this chapter are free. Sign in with Google or Microsoft to start solving.


Core idea: Binary search works whenever you can ask a yes/no question of the middle element and throw away the half that cannot contain the answer. Once you can decide "which side is the target on?" in O(1), the search collapses from O(n) to O(log n) โ€” even when the array is rotated or the structure is subtler than "is this the value?".


The pattern

Every problem here keeps two pointers, lo and hi, and repeatedly inspects mid. The art is choosing the predicate that decides which half survives, and being disciplined about whether you want the first match, the last match, or simply any match.

Three reflexes carry the whole chapter. First, when duplicates or boundaries matter, run binary search twice โ€” once biased left, once biased right โ€” to pin down a range instead of a point. Second, when the array is rotated, at every step one half is guaranteed sorted; compare mid against an endpoint to find that sorted half, then check whether the target lies inside it. Third, when there is no obvious "value to match," search on a derived property โ€” a parity rule, or a comparison of mid to its neighbour โ€” that still cleanly splits the array.

The invariant is what keeps you safe: name what lo and hi mean before the loop, and make sure every branch preserves it.


The problems

Find First and Last Position of Element in Sorted Array โ€” locate the leftmost and rightmost occurrence of a target. Run two boundary searches: one that keeps moving left on a match, one that keeps moving right. Two O(log n) passes give the full range.

Search in Rotated Sorted Array โ€” a sorted array rotated at an unknown pivot. At each mid, one half is sorted; figure out which, decide whether the target falls inside that sorted half, and discard the other.

Find Minimum in Rotated Sorted Array โ€” the minimum is the single point where order breaks. Compare mid to the right endpoint: if mid > right, the dip is to the right; otherwise it is at mid or to its left.

Single Element in a Sorted Array โ€” every element appears twice except one. Pairs sit at indices (even, odd) until the lone element shifts them; use that parity on pairs as the predicate to binary-search the break.

Search in a Sorted Array of Unknown Size โ€” no length is given. First double an exponential bound until it overshoots the target, then binary-search the bracketed range. Still O(log n).


Key takeaways

  • Pick the predicate first. Binary search is "discard the impossible half"; the hard part is the yes/no test at mid, not the loop.
  • Boundaries need two searches. First and last position are two biased binary searches, not one.
  • In a rotated array one half is always sorted. Identify it by comparing mid to an endpoint, then test containment.
  • Search on a property, not just a value. Parity, neighbour comparison, or an exponential bound can all serve as the splitting rule.
  • Why this chapter matters: it builds the binary-search instinct โ€” invariant, predicate, half-discard โ€” that every later chapter reuses.

Core idea: The smallest element is the one place where the order "breaks." Compare a[mid] to the right end a[hi] โ€” if a[mid] > a[hi] the break is to mid's right, otherwise it's at mid or to its left. Halve, repeat, converge.

Problem, rephrased

You run a city subway loop. Stations are numbered in strictly increasing order around a circular line, but your monitoring feed always starts dumping data from whichever station the train currently sits at, then continues around the loop and wraps back to the lowest-numbered station before coming back to the start.

So instead of seeing the clean sequence [10, 20, 30, 40, 50], you might receive [40, 50, 10, 20, 30] โ€” the same values, just rotated so the feed begins partway through.

Your job: given one of these rotated dumps, find the smallest station number (which is exactly where the feed "wrapped around"). The catch โ€” the feed can be huge, so you must do it in O(log n) time. All values are distinct.

Input (rotated dump) Output (minimum) Why
[40, 50, 10, 20, 30] 10 wrap happens between 50 and 10
[30, 40, 50, 10, 20] 10 rotated by 2, min sits at index 3
[20, 30, 40, 50, 10] 10 rotated by 4, min is the last
[10, 20, 30, 40, 50] 10 not rotated โ†’ min is the first
[5] 5 single element

Sign in to continue reading

The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.

Sign in to read the full lesson

Sign in to MAANG.io

Use your Google or Microsoft account โ€” no password to remember.

Continue with Google Continue with Microsoft

Please accept the terms above to continue.