AlgoMaster Logo

Search a 2D Matrix

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

Intuition:

The simplest way to search for a target in a 2D matrix is to iterate through each element until we find the target or exhaust all possibilities. This approach mimics a direct linear search, which is straightforward but inefficient for large matrices.

Code:

2. Binary Search on 2D Matrix

Intuition:

Given that the rows of the matrix are sorted in non-decreasing order and each first integer of a row is greater than the last integer of the previous row, each row can independently be subjected to a binary search to determine if the target exists therein. This approach capitalizes on this sorted property, reducing the search space more efficiently than a linear scan.

Code:

3. Treat 2D Matrix as 1D Array

Intuition:

By treating the 2D matrix as a sorted 1D array, we can perform a single binary search to find the target. The index conversion between the 1D and 2D matrix can be done using simple row and column calculations. This method fully utilizes the sorted property of the entire matrix, leading to an extremely efficient solution.

Code: