Search a 2D matrix II Leetcode Solution
Search a 2D matrix II Leetcode Problem :
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 in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
Example :
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]],
target = 5
Output: true
Search a 2D Matrix || Leetcode Solution :
Constraints :
- m == matrix.length
- n == matrix[i].length
- 1 <= n, m <= 300
- -109 <= matrix[i][j] <= 109
- All the integers in each row are sorted in ascending order.
- All the integers in each column are sorted in ascending order.
- -109 <= target <= 109
Example 1:
- Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
- Output: false
Intuition :
Traversing using corner elemnts;
Approach :
- first choose the corner (either top right or bottom left)….i have chosen bottom left
- Traverse till opposite corner is reaches..
- a) if corner element is equal to target ….return true;
b) if target is smaller than corner elemnt….then the target must be abbove the bottom row…..so bottom row–;
c) if target is greater than corner elemnt….then the target must be on the rigth of left column…..so left column++; - if loop completes means no element found so return false.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Code :
C++
Java
Python
C++
class Solution { public: bool searchMatrix(vector< vector< int>>& matrix, int target) { int n=matrix.size(); int m=matrix[0].size(); int i=0,j=m-1; while(i< n && j>=0) { if(matrix[i][j]==target) return true; else if(matrix[i][j]>target) j--; else i++; } return false; } };
Java
class Solution { public boolean searchMatrix(int[][] matrix, int target) { int r = matrix.length; int c = matrix[0].length; int b = c-1; int l = 0; while(l=0){ if(matrix[l][b]==target){ return true; } else if(matrix[l][b]>target){ b--; } else{ l++; } } return false; } }
Python
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: ROWS, COLS = len(matrix), len(matrix[0]) for row in range(ROWS): if matrix[row][0] <= target and matrix[row][-1] >= target: top, bot = 0, COLS while top < bot: mid = (top + bot) // 2 if target > matrix[row][mid]: top = mid + 1 elif target < matrix[row][mid]: bot = mid else: return True return False
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment