Skip to main content

Find a Solution of Search a 2D Matrix Problem | Java Solution with Explanation | LeetCode

Search a 2D Matrix Problem Solution in Java | Binary Search

Search a 2D Matrix Problem Solution in Java | Binary Search

Problem Description :

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 from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

2D Matrix Java

Example 1 :

Input :
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]
target = 15

Output :
false

Example 2 :

matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]
target = 5

Output :
true

Example 3 :

matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]
target = 34

Output :
true

In this problem, we have given 2 Dimensional Array and integer target. We have to find out if target is present in given matrix or not.

Given matrix elements are sorted so we can easily perform binary search and find out target is present or not.

Here we will see two solutions for this problem.

Solution 1 : Search a 2D Matrix in Java


 import java.util.Scanner;

public class Search2DMatrix {

    public static void main(String[] args) {
       
        Scanner sc = new Scanner(System.in);
       
        System.out.println("Enter row and column");
        int row = sc.nextInt();
        int column = sc.nextInt();
       
        int[][] array = new int[row][column];
       
        System.out.println("Enter array data");
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                array[i][j] = sc.nextInt();
            }
        }
       
        System.out.println("Enter target");
        int target = sc.nextInt();
       
        System.out.println(searchMatrix(array, target));

    }
    
    public static boolean searchMatrix(int[][] matrix, int target) {

        int i = 0;
        int j = matrix[i].length-1;
       
        while (i < matrix.length && j >= 0) {
            if (matrix[i][j] == target) {
                return true;
            } else if (matrix[i][j] > target) {
                j--;
            } else {
                i++;
            }
        }
       
        return false;
    }

}

Solution Explanation :

  • Here we are start searching our target from last column of 1st row. So i = 0 and j = 4-1 = 3 becomes in our above example matrix.
  • In while loop, we have to check for our i and j must not exceed given matrix index.
  • Now check current element is target or not. If not,
  • Go to else if, Check if target is greater than current element than decrement column value by 1.
  • Otherwise increment row by 1.

Example Explanation :

matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]
target = 11

  • i = 0, j = 3
  • 0 < 3 && 3 >= 0 becomes TRUE
    • if (7 == 11) becomes false
    • else if (7 > 11) becomes false
    • else i = 1

  • i  = 1, j = 3
  • 1 < 3 && 3 >= 0 becomes TRUE
    • if (20 == 11) becomes false
    • else if (20 > 11) becomes TRUE
    • j = 2

  • i  = 1, j = 2
  • 1 < 3 && 2 >= 0 becomes TRUE
    • if (20 == 11) becomes false
    • else if (20 > 11) becomes TRUE
    • j = 1

  • i  = 1, j = 1
  • 1 < 3 && 1 >= 0 becomes TRUE
    • if (11 == 11) becomes TRUE
    • return TRUE
 

Solution 2 : Find given target in 2D Matrix using Binary Search in Java


import java.util.Scanner;

public class Search2DMatrix {

    public static void main(String[] args) {
       
        Scanner sc = new Scanner(System.in);
       
        System.out.println("Enter row and column");
        int row = sc.nextInt();
        int column = sc.nextInt();
       
        int[][] array = new int[row][column];
       
        System.out.println("Enter array data");
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                array[i][j] = sc.nextInt();
            }
        }
       
        System.out.println("Enter target");
        int target = sc.nextInt();
       
        System.out.println(searchMatrix(array, target));

    }
    
    public static boolean searchMatrix(int[][] matrix, int target) {

        if (matrix.length == 0) return false;
       
        int rowSize = matrix.length;
        int columnSize = matrix[0].length;
       
        int low = 0;
        int high = (rowSize * columnSize) - 1;
       
        while (low <= high) {
            int mid = (high + low) / 2;
           
            if (matrix[mid/columnSize][mid%columnSize] == target) {
                return true;
            } else if (matrix[mid/columnSize][mid%columnSize] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
       
        return false;
    }

}
 

Solution Explanation :

  • Here we are using Binary Search algorithm for finding solution.
  • Take low as 0 and high as row * column size.
  • Loop until low becomes less than high.
    • Get mid element.
    • Here we are getting mid element through :
      • Row = Divide mid with columnSize
      • Column = Modulo of mid with columnSize
  • If target is less than current element, assign low by mid + 1.
  • Else assign high as mid - 1.

Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static jav...

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...