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

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 ...

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...