Length 2:01Loading the video
Loading the video
Find one number in a grid of sorted rows, where each row starts higher than the row before it ends. Treat the grid as one long sorted list and use binary search, which halves what is left to check at every step.
Narrated by an AI voice.
LeetCode 74 asks you to find one target number in a grid.
Each row is sorted from small to large.
And the first number of every row is bigger than the last number of the row above.
Here is the example from the problem, with three rows and four columns.
Is the number 3 in the grid?
Yes, so we return true.
Is 13 in the grid?
No, so we return false.
The easy answer checks every cell one by one.
With m rows and n columns, that takes m times n checks.
The problem wants something faster, a running time of log of m times n.
Here is the idea.
Read the rows one after another, and you get one long sorted list.
It has twelve numbers, at positions zero to eleven.
A sorted list means we can use binary search.
We never build that list.
We turn a position into a row and a column instead.
The row is the position divided by n, rounded down.
The column is the remainder.
Position six, with four columns, is row one, column two.
That cell holds sixteen.
Now we search for sixteen.
Low starts at zero, and high starts at eleven.
The middle is position five, which holds eleven.
That is too small, so low moves to six.
The new middle is eight, which holds twenty three.
That is too big, so high moves to seven.
The middle is six, which holds sixteen.
We found it in three steps.
Here is the code in JavaScript.
We store the row and column counts, and set low and high.
While low is not bigger than high, we find the middle.
We turn it into a row and a column, and read the value.
We return true on a match, and otherwise move low or high.
If the loop ends, the target is not in the grid.
Each step cuts the search space in half.
So the time is log of m times n, and the extra memory stays constant.
Treat the grid as one sorted list, and binary search it with a division and a remainder.
Binary search: how it works and when to use it
Binary search halves a sorted range at every step, so a million items take about 20 checks. Signals, a worked 2D grid example, code and practice.
Type any algorithm, interview problem or system, and get your own narrated video.
3 free videos with your own AI key. An AI key is a code from an AI company, such as Anthropic or OpenAI. Your own AI account pays for the writing. See pricing
Make a video
Length 2:01
Length 1:13
Length 2:20