Table of Contents
If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
Problem :
Given row wise and column wise sorted matrix ,we need to search element with minimum time complexity.
Solution :
Solution 1:
You can simply search an element in 2D matrix but it will be done in O(R*C) complexity.
Solution 2:
- Iterate over each row
- Do binary search on rows unless you find the element.
- If you do not find the element , return false.
Time complexity : O(C*logR)
Solution 3:
We will use below logic to search an element
- Elements right to current element will be greater than element
- Elements left to current element will be lesser than element
- Elements down to current element will be greater than element
- Elements top to current element will be lesser than element
Algorithm:
- Starts with top right element, so initialise r=0 and c=
sortedMatrix[0].length-1
-
Iterate over matrix with boundary conditions.
-
If current element lets say m is equal to element X, return it.
-
If m < X, go left,so decrease column by 1 (c--).
-
If m > X, go right, so increase row by 1(r++).
Time complexity : O(R+C)
Java program to Search in a row wise and column wise sorted matrix:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package org.arpit.java2blog; public class SearchElementInSortedMatrixMain { public static void main(String[] args) { int[][] sortedMatrix = { { 1, 6, 10, 12, 20 }, { 4, 8, 15, 22, 25 }, { 5, 20, 35, 37, 40 }, { 10, 28, 38, 45, 55 } }; searchElementInSortedMatrix(sortedMatrix, 37); } private static void searchElementInSortedMatrix(int[][] sortedMatrix, int X) { int R = sortedMatrix.length; int C = sortedMatrix[0].length; int r = 0, c = C - 1; // We can go either left or down // left => decrement in columns, 0 will be the bound // down => increment in row, R-1 will be the bound while (r <= R - 1 && c >= 0) { if (sortedMatrix[r][c] == X) { // Found the element System.out.println("Element found at r =" + r + " c=" + c); return; } if (X < sortedMatrix[r][c]) { // move left c = c - 1; } else { // move down r = r + 1; } } System.out.println("Element is not found in sorted matrix"); } } |
1 2 3 |
Element found at r =2 c=3 |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.