Search a 2D Matrix II
Problem Statement
You are given a grid matrix with m rows and n columns, and a number target. The grid has two promises:
- Every row is sorted from left to right (ascending).
- Every column is sorted from top to bottom (ascending).
Unlike Search a 2D Matrix, a row does not have to start after the previous row ends. Return true if target is somewhere in the grid, otherwise false.
A 2D integer array matrix (m rows, n columns) whose rows and columns are each sorted ascending, and an integer target.
true if target is in the matrix, otherwise false.
5 is at row 1, column 1.
20 is not in the grid. Note that row 0 ends with 15 but row 1 starts with 2 — the rows overlap, so this grid is not one sorted line.
- • 1 ≤ m, n ≤ 300 (m rows, n columns)
- • −10^9 ≤ matrix[i][j], target ≤ 10^9
- • Every row is sorted ascending, left to right.
- • Every column is sorted ascending, top to bottom.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Scan all m · n cells and compare each one with target
Each row is sorted, so run a binary search on each row
Start top-right; too big → move left, too small → move down
Loop over every row and every column. Return true the moment a cell equals target.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Binary Search translate into production architectures and low-level memory mechanics.