Search in Row and Column-wise Sorted Matrix
Problem and examples
You are given a 2D matrix where each row and each column is sorted in non-decreasing order. Your task is to search for a given target value in this matrix.
You need to determine whether the target value exists in the matrix or not. Return true if it exists, else return false.
The matrix is not fully sorted overall, but it has a special property:
- Each row is sorted from left to right.
- Each column is sorted from top to bottom.
| Matrix | Target | Output | Description |
|---|---|---|---|
| [[1, 4, 7], [2, 5, 8], [3, 6, 9]] | 5 | true | 5 is present in the middle of the matrix |
| [[10, 20, 30], [15, 25, 35], [27, 29, 37]] | 29 | true | 29 is present in the last row |
| [[1, 2, 3], [4, 5, 6], [7, 8, 9]] | 10 | false | 10 is greater than all elements in the matrix |
| [[1, 2, 3], [4, 5, 6], [7, 8, 9]] | 0 | false | 0 is smaller than all elements in the matrix |
| [[5]] | 5 | true | Single element match |
| [[5]] | 3 | false | Single element does not match |
| [] | 1 | false | Empty matrix has no elements |
Explore Search in Row and Column-wise Sorted Matrix
Load an example or enter your own input. Use the player controls to follow each change.
Understanding the Problem
We are given a 2D matrix where each row and each column is sorted in non-decreasing order. Our goal is to determine whether a specific target value exists in the matrix.
This isn't just any matrix—its sorted nature gives us a big advantage. We don't have to search every cell. Instead, we can intelligently move through the matrix to find the target faster.
Step-by-Step Solution with Example
Step 1: Choose a Starting Point
We begin at the top-right corner of the matrix. Let’s say our matrix is:
int[][] matrix = {
{1, 4, 7, 11},
{2, 5, 8, 12},
{3, 6, 9, 16},
{10,13,14,17}
};
int target = 5;
The element at the top-right is 11. This choice is strategic because it allows us to eliminate either a row or a column based on the comparison with the target.
Step 2: Compare and Move
Compare the current element (starting at matrix[0][3] = 11) with the target:
- If current element equals target → we found it!
- If current element greater than target → move left (since elements to the left are smaller)
- If current element less than target → move down (since elements below are larger)
Step 3: Walk Through the Example
- Start at
matrix[0][3] = 11. 11 > 5 → move left - Now at
matrix[0][2] = 7. 7 > 5 → move left - Now at
matrix[0][1] = 4. 4 < 5 → move down - Now at
matrix[1][1] = 5. Match found!
We found the target in just 4 steps, without checking all 16 elements!
Step 4: Implement the Logic
public boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length;
if (rows == 0) return false;
int cols = matrix[0].length;
int row = 0, col = cols - 1;
while (row < rows && col >= 0) {
if (matrix[row][col] == target) return true;
else if (matrix[row][col] > target) col--;
else row++;
}
return false;
}
Edge Cases
- Empty Matrix: If the matrix is empty or has zero columns, return
falseimmediately. - Single Element: If the matrix has one element, compare it directly with the target.
- Target smaller than all elements: We’ll keep moving left and go out of bounds quickly.
- Target greater than all elements: We’ll move down and exit the matrix without finding it.
- Negative values or duplicates: Still handled correctly, as the sorted structure remains valid.
Finally
This method takes advantage of the matrix's sorted properties. By starting at the top-right, we are always moving closer to our goal and never backtracking. This makes the solution both intuitive and efficient.
The time complexity is O(N + M), where N is the number of rows and M is the number of columns. This is far better than a brute-force O(N * M) search.
For beginners, it’s a great example of how understanding data structure properties helps in writing optimized code.
- Start at the top-right corner of the matrix, i.e.,
row = 0,col = M - 1. - While
row < Nandcol ≥ 0: - → If
mat[row][col] == target, returntrue. - → If
mat[row][col] > target, move left by doingcol--. - → If
mat[row][col] < target, move down by doingrow++. - If the loop ends without finding the target, return
false.
Implementation and efficiency
C implementation
#include <stdio.h>
#include <stdbool.h>
bool searchMatrix(int mat[][3], int rows, int cols, int target) {
int row = 0, col = cols - 1;
while (row < rows && col >= 0) {
if (mat[row][col] == target) return true;
else if (mat[row][col] > target) col--; // Move left
else row++; // Move down
}
return false;
}
int main() {
int mat[3][3] = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}};
int target = 5;
printf("Element found: %s\n", searchMatrix(mat, 3, 3, target) ? "true" : "false");
return 0;
}C++ implementation
#include <iostream>
using namespace std;
bool searchMatrix(int mat[3][3], int rows, int cols, int target) {
int row = 0, col = cols - 1;
while (row < rows && col >= 0) {
if (mat[row][col] == target) return true;
else if (mat[row][col] > target) col--; // Move left
else row++; // Move down
}
return false;
}
int main() {
int mat[3][3] = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}};
int target = 5;
cout << "Element found: " << (searchMatrix(mat, 3, 3, target) ? "true" : "false") << endl;
return 0;
}Python implementation
def search_matrix(matrix, target):
rows = len(matrix)
cols = len(matrix[0])
row, col = 0, cols - 1
while row < rows and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] > target:
col -= 1 # Move left
else:
row += 1 # Move down
return False
mat = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
target = 5
print("Element found:", search_matrix(mat, target))Java implementation
public class MatrixSearch {
public static boolean searchMatrix(int[][] mat, int target) {
int n = mat.length;
int m = mat[0].length;
int row = 0, col = m - 1;
while (row < n && col >= 0) {
if (mat[row][col] == target) {
return true;
} else if (mat[row][col] > target) {
col--; // Move left
} else {
row++; // Move down
}
}
return false;
}
public static void main(String[] args) {
int[][] mat = {
{1, 4, 7},
{2, 5, 8},
{3, 6, 9}
};
int target = 5;
System.out.println("Element found: " + searchMatrix(mat, target));
}
}JavaScript implementation
function searchMatrix(mat, target) {
let rows = mat.length;
let cols = mat[0].length;
let row = 0, col = cols - 1;
while (row < rows && col >= 0) {
if (mat[row][col] === target) {
return true;
} else if (mat[row][col] > target) {
col--; // Move left
} else {
row++; // Move down
}
}
return false;
}
const mat = [[1, 4, 7], [2, 5, 8], [3, 6, 9]];
const target = 5;
console.log("Element found:", searchMatrix(mat, target));Go implementation
package main
import (
"fmt"
)
func searchMatrix(mat [][]int, target int) bool {
rows := len(mat)
cols := len(mat[0])
row, col := 0, cols-1
for row < rows && col >= 0 {
if mat[row][col] == target {
return true
} else if mat[row][col] > target {
col--
} else {
row++
}
}
return false
}
func main() {
mat := [][]int{{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}
target := 5
fmt.Println("Element found:", searchMatrix(mat, target))
}Rust implementation
fn search_matrix(mat: &Vec<Vec<i32>>, target: i32) -> bool {
let rows = mat.len();
let cols = mat[0].len();
let (mut row, mut col) = (0, cols - 1);
while row < rows && col < cols {
if mat[row][col] == target {
return true;
} else if mat[row][col] > target {
if col == 0 { break; }
col -= 1;
} else {
row += 1;
}
}
false
}
fn main() {
let mat = vec![vec![1, 4, 7], vec![2, 5, 8], vec![3, 6, 9]];
let target = 5;
println!("Element found: {}", search_matrix(&mat, target));
}Kotlin implementation
fun searchMatrix(mat: Array<IntArray>, target: Int): Boolean {
var row = 0
var col = mat[0].size - 1
while (row < mat.size && col >= 0) {
when {
mat[row][col] == target -> return true
mat[row][col] > target -> col--
else -> row++
}
}
return false
}
fun main() {
val mat = arrayOf(
intArrayOf(1, 4, 7),
intArrayOf(2, 5, 8),
intArrayOf(3, 6, 9)
)
val target = 5
println("Element found: ${searchMatrix(mat, target)}")
}Swift implementation
func searchMatrix(_ mat: [[Int]], _ target: Int) -> Bool {
var row = 0
var col = mat[0].count - 1
while row < mat.count && col >= 0 {
if mat[row][col] == target {
return true
} else if mat[row][col] > target {
col -= 1
} else {
row += 1
}
}
return false
}
let mat = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
let target = 5
print("Element found: \(searchMatrix(mat, target))")TypeScript implementation
function searchMatrix(mat: number[][], target: number): boolean {
let rows = mat.length;
let cols = mat[0].length;
let row = 0, col = cols - 1;
while (row < rows && col >= 0) {
if (mat[row][col] === target) {
return true;
} else if (mat[row][col] > target) {
col--;
} else {
row++;
}
}
return false;
}
const mat: number[][] = [[1, 4, 7], [2, 5, 8], [3, 6, 9]];
const target = 5;
console.log("Element found:", searchMatrix(mat, target));Time complexity
| Case | Time | Explanation |
|---|---|---|
| best case | O(1) | When the target is found at the starting cell (top-right corner). |
| average case | O(N + M) | In each step, we either eliminate a row or a column, leading to at most N + M steps. |
| worst case | O(N + M) | In the worst case, the search visits one full row and one full column without finding the target. |
Space complexity
O(1)
Only a few extra variables are used for row and column tracking, with no additional memory.