Back to Practice Dashboard
Top 150 InterviewEasy

Search a 2D Matrix

Learn how to solve the 'Search a 2D Matrix' problem. This detailed resource details brute force and optimized approaches.

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?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

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

Open in Editor