Search an Element in a Sorted 2D Matrix - Java Solution

1. Introduction

In this post, we'll explore an efficient algorithm to search for a value in a sorted 2D matrix using Java. This problem is a great example of applying binary search in a two-dimensional context, considering the sorted nature of the matrix.

Problem

Given an m x n matrix where each row is sorted from left to right and the first integer of each row is greater than the last integer of the previous row, write an algorithm to search for a target value within this matrix.

Examples:

Input:

matrix = [

[1, 5, 9, 11],

[13, 16, 19, 24],

[28, 30, 38, 50]

],

target = 5

Output: true

Input:

matrix = [

[1, 5, 9, 11],

[13, 16, 19, 24],

[28, 30, 38, 50]

],

target = 12

Output: false

2. Solution Steps

1. Treat the 2D matrix as a flattened 1D array and apply binary search.

2. Calculate the middle element's row and column using index manipulation.

3. Compare the target with the middle element and adjust the search range accordingly.

4. Continue this process until the target is found or the search space is exhausted.

5. Return true if the target is found, otherwise return false.

3. Code Program

public class Solution {
    public static void main(String[] args) {
        int[][] matrix1 = {
            {1,  5,  9,  11},
            {13, 16, 19, 24},
            {28, 30, 38, 50}
        };
        int target1 = 5;

        int[][] matrix2 = {
            {1,  5,  9,  11},
            {13, 16, 19, 24},
            {28, 30, 38, 50}
        };
        int target2 = 12;

        System.out.println("Target " + target1 + " found: " + searchMatrix(matrix1, target1));
        System.out.println("Target " + target2 + " found: " + searchMatrix(matrix2, target2));
    }

    // Method to search the matrix
    public static boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; // Check for empty matrix

        int rows = matrix.length, cols = matrix[0].length;
        int low = 0, high = rows * cols - 1;

        // Binary search
        while (low <= high) {
            int mid = low + (high - low) / 2; // Calculate mid index
            int midValue = matrix[mid / cols][mid % cols]; // Convert 1D index to 2D coordinates

            if (midValue == target) { // Check if midValue is the target
                return true;
            } else if (midValue < target) { // Adjust search range
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }

        return false; // Target not found
    }
}

Output:

Target 5 found: true
Target 12 found: false

Explanation:

In the first example, the target 5 is present in the matrix, so the output is true. The algorithm flattens the matrix into a virtual 1D array and applies binary search. 

For the second example, target 12 is not in the matrix, resulting in a false. This method efficiently searches the matrix with a time complexity of O(log(mn)), where m and n are the dimensions of the matrix.

Comments