πDay 4. Search in a Row-Wise Sorted Matrix π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given a row-wise sorted 2D matrix mat[][] of size n x m and an integer x, determine whether the element x is present in the matrix.
Note: A row-wise sorted matrix implies that each row is sorted in non-decreasing order.
π Example Walkthrough:
Input:
mat[][] = [[3, 4, 9], [2, 5, 6], [9, 25, 27]]
x = 9Output:
trueExplanation: 9 is present in the matrix, so the output is true.
Input:
mat[][] = [[19, 22, 27, 38, 55, 67]]
x = 56Output:
falseExplanation: 56 is not present in the matrix.
Input:
mat[][] = [[1, 2, 9], [65, 69, 75]]
x = 91Output:
falseExplanation: 91 is not present in the matrix.
Constraints
$(1 \leq n, m \leq 1000)$
$(1 \leq \text{mat}[i][j] \leq 10^5)$
$(1 \leq x \leq 10^5)$
π― My Approach:
Iterate Through Rows: Loop through each row of the matrix. Since each row is sorted, we can efficiently determine if the target
xexists using binary search.Binary Search for Each Row: For each row:
Use the
binary_searchfunction (in C++) or equivalent methods in other languages to locatex.The binary search divides the row into halves and compares the middle element with
x:If the middle element matches
x, returntrue.If the middle element is greater than
x, continue searching in the left half of the row.Otherwise, continue searching in the right half.
Final Check: If no row contains
xafter checking all rows, returnfalse.
π Time and Auxiliary Space Complexity
Expected Time Complexity:
$(O(n \cdot \log m))$, where $(n)$ is the number of rows and $(m)$ is the number of columns. This is because for each row, a binary search runs in $(O(\log m))$.
Expected Auxiliary Space Complexity:
$(O(1))$, as the binary search operates in constant space.
π Solution Code
Code (Cpp)
class Solution {
public:
bool searchRowMatrix(vector<vector<int>>& mat, int x) {
for (auto& row : mat) {
if (binary_search(row.begin(), row.end(), x)) return true;
}
return false;
}
};Code (Java)
class Solution {
public boolean searchRowMatrix(int[][] mat, int x) {
for (int[] row : mat) {
if (Arrays.binarySearch(row, x) >= 0) {
return true;
}
}
return false;
}
}Code (Python)
class Solution:
def searchRowMatrix(self, mat, x):
for row in mat:
if x in row:
return True
return Falseπ― Contribution and Support:
For discussions, questions, or doubts related to this solution, please visit my LinkedIn:- Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.
β Star this repository if you find it helpful or intriguing! β
πVisitor Count
Last updated