Search in 2D matrix

In this post, we will discuss two approaches to searching for an element in a sorted 2D matrix efficiently.
π‘ Brute Force Approach
The simplest way to search for an element is to traverse the entire matrix row by row and column by column.
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rows = matrix.size();
if (rows == 0) return false;
int cols = matrix[0].size();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == target)
return true;
}
}
return false;
}
Time Complexity:
O(m Γ n) (where
m
is the number of rows andn
is the number of columns)This is because we check every element.
Space Complexity:
- O(1) (since we are not using extra space)
While this method works, it is not optimal for large matrices. Let's improve it!
Optimized Approach: Binary Search
Since the matrix is sorted in row-major order, we can flatten it into a virtual 1D array and apply binary search. However, we donβt actually need to store it as a 1D arrayβwe can calculate the row and column indices using a formula.
π’ Understanding the Formula
Consider this matrix:
1 2 3 4
5 6 7 8
9 10 11 12
We can treat it as a 1D array:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Indexing formula:
Row =
mid / cols
β Finds which row themid
index belongs to.Column =
mid % cols
β Finds the column within that row.
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rows = matrix.size();
int cols = matrix[0].size();
int low = 0, high = (rows * cols - 1); // Total elements: m*n
while (low <= high) {
int mid = (low + high) / 2;
int row = mid / cols;
int col = mid % cols;
if (matrix[row][col] == target)
return true;
else if (matrix[row][col] < target)
low = mid + 1;
else
high = mid - 1;
}
return false;
}
Time Complexity:
- O(log(m Γ n)) β Since we are using binary search, we reduce the search space logarithmically.
Space Complexity:
- O(1) β No extra space is used.
KEY POINTS :
β
Brute Force: O(m Γ n) (Inefficient)
β
Binary Search: O(log(m Γ n)) (Optimal)
This binary search method makes searching for an element in a sorted 2D matrix super fast! π
Hope you found this useful! Stay tuned for more DSA solutions. ππ‘
problem link: https://leetcode.com/problems/search-a-2d-matrix/description/
Subscribe to my newsletter
Read articles from Nikhitha directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Nikhitha
Nikhitha
π Software Developer | DSA Enthusiast | Problem Solver πΉ Sharing daily DSA solutions, coding insights, and interview prep πΉ Passionate about writing optimized & bug-free code