</> 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

Peaks and 2D

What is this?

Here binary search escapes the sorted list entirely. A "peak" is just a value bigger than its neighbours โ€” think of hiking and always stepping toward the higher of the two sides; you're guaranteed to reach a summit, and you get there in a handful of steps instead of walking the whole ridge. The "2D" half plays a different game: a grid whose rows are sorted and stacked in order is secretly one long sorted line in disguise, so you can read row and column off a single position and search it like any ordinary array.

flowchart TD A["Pick the middle"] --> B["Compare with a neighbour"] B --> C["Move toward the higher side"] C --> D["Window shrinks by half"] D --> A

๐Ÿ’ก Fun fact: The "always walk uphill" idea behind peak-finding is the oldest optimization method there is โ€” hill climbing. It powers everything from autofocus on your phone camera hunting the sharpest image to early machine-learning models tuning their own weights.

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


Core idea: Binary search does not require a fully sorted array โ€” it only requires that the middle element tell you which half to keep. When data has a local slope you can climb toward higher ground, and when a 2D grid is sorted row by row you can pretend it is one long sorted line. Both turn an O(n) or O(mn) scan into O(log n).


The pattern

The unifying move is the same as classic binary search: probe the middle, decide which half cannot hold the answer, and discard it. What changes is the signal you read at mid.

For peaks, there is no global order, but there is direction. Compare mid to its neighbour: the slope is rising on one side, falling on the other, and a peak is guaranteed to exist in the rising direction. So you climb toward the higher neighbour โ€” that half always contains a peak, and you keep halving until the pointers meet on one.

For grids, the trick is to flatten. A matrix whose rows are sorted and whose every row starts after the previous one ends behaves exactly like a single sorted array of length m ร— n. Map a virtual index k to (k / cols, k % cols) and run an ordinary binary search over 0 โ€ฆ mยทn โˆ’ 1. When only columns or only rows are sorted, binary-search along the sorted dimension and scan the other.


The problems

Peak Index in a Mountain Array โ€” the array strictly rises then strictly falls. Compare mid to mid + 1: if it is still rising, the peak is to the right, otherwise it is at mid or to its left. Climb toward the higher neighbour until the window closes on the summit.

Find a Peak Element II โ€” a 2D peak is a cell greater than all four neighbours. Binary search on columns: pick the middle column, find its maximum row, and move toward whichever side has a larger neighbour โ€” that side is guaranteed to contain a 2D peak. Each step is O(m) to scan a column, giving O(m log n).

Search a 2D Matrix โ€” rows sorted and each row's first value exceeds the prior row's last. Treat the grid as one sorted array of mยทn elements; convert the midpoint index to (row, col) and binary-search normally for O(log(mยทn)).


Key takeaways

  • Sortedness is optional; a decisive midpoint is not. A local slope is enough to binary-search a peak.
  • Climb toward the higher neighbour. A peak always lies on the rising side, so that half is safe to keep.
  • Flatten a sorted grid into one virtual array. Index math (k / cols, k % cols) turns 2D search into 1D.
  • Search the sorted dimension, scan the other. For peak-in-a-grid, binary-search columns and scan each column's max.
  • Why this chapter matters: it breaks the myth that binary search needs full order, opening it up to slopes, grids, and any data with a reliable directional signal.

Search a 2D Matrix

Core idea: A fully row-major-sorted matrix is a sorted 1D array wearing a grid costume โ€” flatten the index with (i // n, i % n) and run one ordinary binary search.

Problem, rephrased

You're handed a grid of numbers laid out like text on a page: you read left-to-right across a row, and when you drop to the next row, every value there is larger than everything in the row above. So if you swept the whole grid in reading order โ€” row 0 left-to-right, then row 1 left-to-right, and so on โ€” the values would come out in strictly increasing order.

Given such a grid and a target, answer one yes/no question: is target somewhere in the grid?

Concretely, picture a warehouse shelf-labeling system. Bins are arranged in a grid, and they were numbered in reading order so a picker can walk them in sequence. You want to know if bin #target exists on this shelf.

matrix target Output Why
[[1,4,7,11],[15,20,23,28],[31,36,40,45]] 23 True sits at row 1, col 2
[[1,4,7,11],[15,20,23,28],[31,36,40,45]] 30 False falls between 28 and 31
[[1,4,7,11],[15,20,23,28],[31,36,40,45]] 45 True last cell, bottom-right
[[5]] 5 True single cell, direct hit
[[1,3],[5,7]] 0 False smaller than everything

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.