304 North Cardinal St.
Dorchester Center, MA 02124

# Search a 2D Matrix LeetCode Solution

## Problem – Search a 2D Matrix LeetCode Solution

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.

Example 1:

``````Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
``````

Example 2:

``````Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
``````

Constraints:

• `m == matrix.length`
• `n == matrix[i].length`
• `1 <= m, n <= 100`
• `-104 <= matrix[i][j], target <= 104`

## Search a 2D Matrix LeetCode Solution in C++

``````class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rows = matrix.size(),
cols = matrix[0].size(),
row = 0, col = cols - 1;

while (row < rows && col > -1) {
int cur = matrix[row][col];
if (cur == target) return true;
if (target > cur) row++;
else col--;
}

return false;
}
};
``````

## Search a 2D Matrix LeetCode Solution in Java

``````  public boolean searchMatrix(int[][] matrix, int target) {
int i = 0, j = matrix[0].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;
}
``````

## Search a 2D Matrix LeetCode Solution in Python

``````class Solution:
# @param matrix, a list of lists of integers
# @param target, an integer
# @return a boolean
# 8:21
def searchMatrix(self, matrix, target):
if not matrix or target is None:
return False

rows, cols = len(matrix), len(matrix[0])
low, high = 0, rows * cols - 1

while low <= high:
mid = (low + high) / 2
num = matrix[mid / cols][mid % cols]

if num == target:
return True
elif num < target:
low = mid + 1
else:
high = mid - 1

return False
``````
##### Search a 2D Matrix LeetCode Solution Review:

In our experience, we suggest you solve this Search a 2D Matrix LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Search a 2D Matrix LeetCode Solution

Find on Leetcode

##### Conclusion:

I hope this Search a 2D Matrix LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions