Search a 2D Matrix II LeetCode

 Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:


Integers in each row are sorted in ascending from left to right.

Integers in each column are sorted in ascending from top to bottom.

 


Example 1:



Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5

Output: true

Example 2:



Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20

Output: false



Approach Used (Search from Top-Right Corner)

  1. Start from the top-right corner of the matrix (row = 0, col = last index).

  2. Compare the element with the target:

    • If it matches, return true.

    • If the target is smaller, move left (decrease col).

    • If the target is larger, move down (increase row).

  3. Continue this process until either:

    • The element is found (return true).

    • The indices go out of bounds (return false).

Time Complexity:

  • O(m + n) → At worst, we traverse m rows and n columns once.

This is an efficient approach for searching in a sorted 2D matrix. 🚀


class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
       
        // Start from the top-right corner
        int row = 0;
        int col = matrix[0].length - 1;

        // Traverse the matrix within valid bounds
        while (row < matrix.length && col >= 0) {
           
            // If the target is found, return true
            if (matrix[row][col] == target) return true;
           
            // If the target is smaller, move left (decrease column)
            else if (target < matrix[row][col]) {
                col--;
            }
            // If the target is greater, move down (increase row)
            else {
                row++;
            }
        }
       
        // If the loop ends, the target was not found
        return false;
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence