</> 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: When you can't see the end of a sorted source, double your reach until you overshoot the target โ€” that hands you a small window to binary-search inside.

Binary search is wonderful, but it needs two things: a sorted sequence and a known hi bound. Here we keep the sorting but lose the bound. The fix is a two-phase move: first gallop outward to fence in a window that must contain the answer, then run an ordinary binary search inside that window.


Problem, rephrased

You're reading from a temperature-logging probe that streams readings into a sorted store (readings only ever go up over a session, so the values are non-decreasing โ€” for simplicity here, strictly increasing and unique). You don't get a length. You get one method:

  • reader.get(i) โ†’ returns the value at index i, or a huge sentinel (we'll use 2147483647, i.e. 2**31 - 1, the same value LeetCode-style readers use) when i is past the end of the data.

Given a target reading, return the index where it lives, or -1 if it's not there. You may not call len() โ€” the size is genuinely unknown.

Input (reader wraps) target Output Why
[-1, 0, 3, 5, 9, 12] 9 4 9 sits at index 4
[-1, 0, 3, 5, 9, 12] 2 -1 2 is never present
[2, 5, 5, 5, 8] (here unique-only) 2 0 target sits at the very front
[7, 14, 22, 35, 51, 68, 90] 90 6 target is the last real element

The catch is purely the unknown size. If you knew the length n, this would be a textbook binary search.


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.