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

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

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...