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

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

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...