878378. Search in a row-wise sorted matrix

Easy

Search in a row-wise sorted matrix

Summary

Given a row-wise sorted matrix, find an element that is equal to a given target value. The matrix consists of N rows and M columns. Each row is sorted in ascending order. We need to write an algorithm that efficiently searches for the target value in this matrix.

The key concepts involved are binary search and arrays.

Detailed Explanation

To solve this problem, we can use a modified version of binary search. Since each row is sorted, we can treat the entire matrix as if it were one large array, where each element is represented by its row number and column index. We start by performing a binary search on the first row to find the target value or determine that it's not present in this row.

If the target value is found in the first row, we can return the coordinates of the element. If the target value is not found in the first row, we know that it must be present in one of the subsequent rows. In this case, we use the middle element of the first row as a pivot and divide the remaining rows into two halves based on whether their first elements are less than or greater than the pivot.

We repeat this process until we find the target value or determine that it's not present in any of the rows. The time complexity of this algorithm is O(log(N)), where N is the number of rows, and the space complexity is O(1), since we only need a constant amount of space to store the pivot and the indices.

Here's a step-by-step breakdown of the solution:

  1. Initialize two pointers, low and high, to represent the range of rows that still contain the target value.
  2. Perform a binary search on the first row to find the target value or determine that it's not present in this row.
  3. If the target value is found in the first row, return the coordinates of the element.
  4. If the target value is not found in the first row, calculate the pivot as the middle element of the first row.
  5. Update low and high based on whether the first elements of the remaining rows are less than or greater than the pivot.
  6. Repeat steps 2-5 until we find the target value or determine that it's not present in any of the rows.

Optimized Solutions

Java

View on GeeksforGeeks
public int searchMatrix(int[][] matrix, int target) {
    if (matrix == null || matrix.length == 0) {
        return -1;
    }

    int N = matrix.length;
    int M = matrix[0].length;

    int low = 0;
    int high = N - 1;

    while (low <= high) {
        int mid = (low + high) / 2;
        if (matrix[mid][0] == target) {
            return mid * M + 0;
        } else if (target < matrix[mid][0]) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }

    return -1;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.