Search a 2D Matrix
Module 15 · Matrix / 2D Traversal
Problem
You are given an m × n integer matrix with two properties:
- Each row is sorted in ascending order (left to right).
- The first integer of each row is greater than the last integer of the previous row.
Given a target, return true if it appears in the matrix and false
otherwise. (LeetCode 74.)
Examples
Example 1
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3OutputtrueExample 2
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13OutputfalseConstraints
1 ≤ m, n ≤ 100, values in ±10⁴. Both stated properties matter — read them carefully before attempting, because together they say something stronger than "each row is sorted."
Attempt it first
Before writing anything, stare at the two properties and ask what they jointly imply about the matrix read in row-major order (lesson 1 / 2: row 0 left-to-right, then row 1, and so on). Property 1 sorts within a row; property 2 says every row starts above where the previous row ended. Chain them. What does the entire row-major sequence of values look like? If you see it, you'll know exactly which Module 13 technique applies and you're most of the way done. Try to name the structure before revealing the hint.