Search a 2D Matrix II (Young Tableau)

Medium Binary Search 2D Binary Search + Step Search Original on LeetCode

Search a 2D Matrix II (Young Tableau) is a medium binary search problem solved with the 2d binary search + step search pattern. The best approach, optimal (staircase / step search), runs in O(m + n) time and O(1) space. Below are 2 approaches in Java, from binary search each row up.

Problem

In an m × n matrix (a Young tableau), every row is sorted left to right and every column is sorted top to bottom. Decide whether target is present.

Examples

Example 1

Input
matrix = [[1,4,7],[2,5,8],[3,6,9]], target = 6
Output
true

Example 2

Input
matrix = [[1,4,7],[2,5,8],[3,6,9]], target = 10
Output
false

Constraints

  • 1 <= m, n <= 300
  • Each row is sorted left to right, each column top to bottom.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.

ApproachTimeSpace
Binary search each rowO(m log n)O(1)
Optimal (staircase / step search)O(m + n)O(1)

1Binary search each row

TimeO(m log n)
SpaceO(1)

Every row is sorted, so binary search each one.

  1. For each row, run binary search for target.
Java
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        for (int[] row : matrix) {
            int lo = 0, hi = row.length - 1;
            while (lo <= hi) {
                int mid = (lo + hi) >>> 1;
                if (row[mid] == target) return true;
                if (row[mid] < target) lo = mid + 1; else hi = mid - 1;
            }
        }
        return false;
    }
}

Edge cases to test

  • Target smaller than the top-left or larger than the bottom-right
  • Single row or column

Hints

Hint 1

At the top-right corner, one move eliminates a whole row or a whole column.

FAQ

What is the best time complexity for Search a 2D Matrix II (Young Tableau)?

Optimal (staircase / step search) runs in O(m + n) time and O(1) extra space.

Which pattern does Search a 2D Matrix II (Young Tableau) use?

It is a binary search problem that uses the 2d binary search + step search pattern. Other problems with the same pattern: Row with max 1s, Search a 2D Matrix.

Is there a brute force solution for Search a 2D Matrix II (Young Tableau)?

Yes. Binary search each row takes O(m log n) time and O(1) space. Every row is sorted, so binary search each one.

Which edge cases should I test for Search a 2D Matrix II (Young Tableau)?

Target smaller than the top-left or larger than the bottom-right; Single row or column.