Top 150 InterviewEasy

Search a 2D Matrix

Detailed guide and Python implementation for the 'Search a 2D Matrix' problem.

Problem Statement

Easy

You are given an m x n integer matrix matrix with the following two properties:

- Each row is sorted in non-decreasing order.

- The first integer of each row is greater than the last integer of the previous row.

Given an integer target, return True if target is in matrix or False otherwise.

You must write a solution in O(log(m * n)) time complexity.

Write a function searchMatrix(matrix: List[List[int]], target: int) -> bool.

Constraints
  • m == len(matrix)
  • n == len(matrix[i])
  • 1 <= m, n <= 100
  • -10^4 <= matrix[i][j], target <= 10^4

Examples

Example 1
Input
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], target = 3
Output
True
Explanation

3 is found in the first row at index 1.

Example 2
Input
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], target = 13
Output
False
Explanation

13 is not present in the matrix.

Need a Hint?
Consider using Binary Search-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.