DSA AnimatorREVISION VIDEOS
← Back to problems
New

Search a 2D Matrix — LeetCode 74 video explanation

Each row is sorted, and the first number of each row is bigger than the last number of the row before. Return true if the target is in the matrix.

Loading videos…

DSA Animator › DSA Revision › Matrix › Search a 2D Matrix

Key moments in the Search a 2D Matrix video

0:04Problem0:12Example0:18Brute force0:25Key idea0:38Dry run1:00Code1:16Takeaway

What you will learn

Remember: a matrix sorted row after row is one long sorted array. Divide and mod by the column count to find the cell. The video solves Search a 2D Matrix (LeetCode 74, Medium) with the Binary Search pattern from the Matrix topic, and you can replay every step in the interactive Search a 2D Matrix animation.

Search a 2D Matrix video transcript

Problem

Each row is sorted, and the first number of each row is bigger than the last number of the row before. Return true if the target is in the matrix.

Example

In this 3 by 4 matrix, the target 3 is present, at row 0, column 1.

Brute force

Checking every cell is O of m times n. But the rules mean the whole matrix is one sorted list, read row by row.

Key idea

Binary search over positions 0 to m times n minus 1. Turn a position into a cell with row equal to position divided by the number of columns, and column equal to position mod the number of columns.

Dry run

Low is 0 and high is 11, so mid is 5, which is row 1, column 1, holding 11. 11 is bigger than 3, so high becomes 4. Mid is 2, row 0, column 2, holding 5, still bigger, so high becomes 1. Mid is 0, holding 1, which is smaller, so low becomes 1. Mid is 1, holding 3, which is the target.

Code

In code, set low to 0 and high to m times n minus 1. Compute mid, and read the matrix at mid divided by n and mid mod n. Return true on a match, or move low or high like a normal binary search. It's O of log of m times n time and O of 1 space.

Takeaway

Remember: a matrix sorted row after row is one long sorted array. Divide and mod by the column count to find the cell.

More Matrix revision videos

← All 185 DSA revision videos