Search a 2D Matrix
Detailed guide and Python implementation for the 'Search a 2D Matrix' problem.
1. Concept Overview
The 'Search a 2D Matrix' problem is a key challenge in the Binary Search section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Search a 2D Matrix.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Search a 2D Matrix carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
Problem Statement
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.
- •m == len(matrix)
- •n == len(matrix[i])
- •1 <= m, n <= 100
- •-10^4 <= matrix[i][j], target <= 10^4
Examples
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], target = 3
True
3 is found in the first row at index 1.
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], target = 13
False
13 is not present in the matrix.
Need a Hint?
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.
Interview Insights & Variations
Complexity Analysis Breakdown
Why Time: Directly evaluates all possibilities.
Why Space: Uses standard local memory.
Why Time: Optimized paths reduce total operations.
Why Space: May trade memory for speed.
Optimized Solution Python Code
Optimized Solution Python Code
def search_matrix_opt(matrix, target):
if not matrix or not matrix[0]: return False
ROWS, COLS = len(matrix), len(matrix[0])
top, bot = 0, ROWS - 1
while top <= bot:
row = (top + bot) // 2
if target > matrix[row][-1]:
top = row + 1
elif target < matrix[row][0]:
bot = row - 1
else:
break
if not (top <= bot): return False
row = (top + bot) // 2
l, r = 0, COLS - 1
while l <= r:
m = (l + r) // 2
if target > matrix[row][m]:
l = m + 1
elif target < matrix[row][m]:
r = m - 1
else:
return True
return FalseBrute Force Code (Spoiler Guarded)
Brute Force Code (Spoiler Guarded)
def search_matrix_brute(matrix, target):
for row in matrix:
if target in row: return True
return FalseAlgorithm Pattern Checklist
When dealing with Binary Search data patterns.
Core Prerequisites
Revision Key Notes
Common Mistakes & Pitfalls
Related Questions
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Variables & Data Types Explained
Understand Python variables and core data types (strings, integers, floats, booleans). A complete beginner guide to memory assignment in Python.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python Dictionary Methods
Learn Python dictionary methods. Complete reference guide for key-value pair insertions, retrievals, updates, and checks.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.