Welcome back! In our last lesson, we adapted binary search to handle a partially ordered structure—a rotated sorted array. The key was to find a property (one sorted half) that allowed us to confidently eliminate a portion of the search space. We're going to continue this theme of searching in partially ordered data structures, but this time, in two dimensions.
Today's lesson focuses on a classic interview problem: searching for a value in a matrix where each row and each column is sorted. Your goal is to learn an efficient strategy that leverages this special structure to eliminate an entire row or column with every comparison, avoiding a slow, brute-force search. This technique is often called "Staircase Search" or "Saddleback Search."
The Problem: A Special Kind of Matrix
Imagine you are given an m x n matrix with the following properties:
- Integers in each row are sorted in ascending order from left to right.
- Integers in each column are sorted in ascending order from top to bottom.
Here's an example:
Notice that while rows and columns are sorted, the matrix as a whole is not. For instance, matrix[0][4] (15) is greater than matrix[1][0] (2). This means we can't simply treat the matrix as a giant sorted 1D array and apply a standard binary search.
From Brute Force to a Better Idea
How would we find a target value, say 5, in this matrix?
-
Brute Force: The simplest way is to iterate through every single cell. For an
m x nmatrix, this is an approach. It's correct, but we can do better by using the sorted property. -
A Better Approach: Since each row is a sorted array, we could perform a binary search on each one. This would involve
mbinary searches, each taking time, for a total time complexity of . This is a significant improvement, but it doesn't use the fact that the columns are also sorted.
The take U forward video provides a great overview of these initial thoughts and sets the stage for the optimal solution.
BS-25. Search in a 2D Matrix - II | Binary Search on 2D
Watch the first few minutes of this video to understand the problem statement and the limitations of the brute-force and row-wise binary search approaches.
Pay close attention to the properties of the matrix as explained from the problem statement. Then, follow the discussion on the brute-force method and the improved, but still suboptimal, approach of binary searching each row.
The Optimal Approach: Eliminate a Row or Column
The most efficient solution comes from a clever insight about where to start our search. If we start at the top-left corner, and our target is larger, we don't know whether to move right or down. Both directions contain larger numbers. The same ambiguity exists at the bottom-right corner if our target is smaller.
However, if we start at the top-right corner (or bottom-left), our choices become unambiguous. Let's start at matrix[0][n-1]. Let this element be current.
- If
target == current, we've found our element. - If
target < current, the target cannot be in the current column, because all elements belowcurrentare even larger. We can safely eliminate the entire last column and move one step to the left (col--). - If
target > current, the target cannot be in the current row, because all elements to the left ofcurrentare smaller. We can safely eliminate the entire current row and move one step down (row++).
This logic guarantees that in every step, we discard either a full row or a full column from our search space. This process continues until we find the target or our pointers move out of the matrix bounds.
The following image illustrates the decision to move left when the current element is greater than the target.

The video from take U forward has an excellent segment that explains why the top-right and bottom-left corners are the ideal starting points for this elimination strategy.
BS-25. Search in a 2D Matrix - II | Binary Search on 2D
Watch this segment to understand the core intuition behind the optimal algorithm. The presenter explains why certain starting points are better than others for making decisive eliminations.
Focus on the part from where the presenter analyzes the different corners of the matrix as potential starting points. This is the conceptual heart of the algorithm.
The "Staircase Search" Algorithm in Action
This search pattern traces a path that looks like a staircase, which is why it's often called "Staircase Search".

To solidify this, the following animated video provides a very clear, step-by-step walkthrough of the entire process. Seeing the pointers i and j move and the logic applied at each step is extremely helpful for building confidence.
Search in a row and column wise sorted matrix | Animation
Watch this detailed, animated walkthrough. It visualizes the entire algorithm, from initializing the pointers to finding the target value.
The most important part is the main demonstration. Start watching from the beginning of the demo, which shows how the row and column pointers (i and j) are updated based on comparing the current matrix element with the target key.
Implementation and Complexity
Now let's look at how to translate this logic into code. The article from GeeksforGeeks provides a concise explanation and a JavaScript implementation.
Search in a row wise and column wise sorted matrix - GeeksforGeeks
This resource explains the logic behind the top-right starting position and provides a clean implementation.
Read the section "[Expected Approach] Eliminating rows or columns". Focus on the three possible cases described in the list and study the provided JavaScript code snippet that implements this logic.
As mentioned, starting from the bottom-left corner works just as well. The logic is slightly different but follows the same principle of elimination:
- Start at
matrix[m-1][0]. - If
target > current, the target can't be in this column (values above are smaller), so move right (col++). - If
target < current, the target can't be in this row (values to the right are larger), so move up (row--).
This GitHub resource provides an explanation for the bottom-left approach and includes a TypeScript implementation, which is perfect for your preferred language.
This resource shows the alternative approach of starting from the bottom-left corner.
Read the "Solution 2: Search from Bottom-Left or Top-Right" section. The logic described uses different pointer movements. Pay close attention to the TypeScript implementation, which shows how this alternative is coded.
Complexity Analysis
- Time Complexity: In each step, we either increment the row index or decrement the column index. The row index starts at
0and goes up tom-1, and the column index starts atn-1and goes down to0. In the worst case, the path will traverse from one corner to the opposite, covering at mostmrows andncolumns. Therefore, the total number of steps is at mostm + n, giving a time complexity of . This is a huge improvement over . - Space Complexity: We only need to store the row and column indices. This requires a constant amount of extra space, so the space complexity is .
Conclusion
In this lesson, we've extended our search skills to two dimensions. While the problem might seem like a candidate for a complex binary search variant, the most elegant solution comes from a different kind of elimination strategy.
Here are the key takeaways:
- A matrix with sorted rows and columns has a special structure that can be exploited for efficient searching.
- The key is to start at a corner where comparisons lead to unambiguous decisions. The top-right or bottom-left corners are ideal for this.
- By comparing the target with the element at the current position, you can eliminate an entire row or column at each step.
- This "Staircase Search" algorithm achieves a time complexity of with space, which is optimal.
- This lesson highlights a crucial theme in algorithms: the principle of elimination is the heart of efficient searching, even if the implementation doesn't look like a classic
while (left <= right)binary search.
In our next and final lesson for this module, we will explore one more powerful and abstract application of binary search: "binary searching the answer," where we search for a solution within a range of possibilities rather than for an element in a data structure.
Can't find a good explanation? Sign up and we'll make it for you
Sign up