Search a 2D Matrix II – Leetcode Solution

In this post, we are going to solve the 240. Search a 2D Matrix II problem of Leetcode. This problem 240. Search a 2D Matrix II is a Leetcode medium level problem. Let’s see the code, 240. Search a 2D Matrix II – Leetcode Solution.

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 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 = 5
Output: true

Example 2 :

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

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

Now, let’s see the code of 240. Search a 2D Matrix II – Leetcode Solution.

Search a 2D Matrix II – Leetcode Solution

240. Search a 2D Matrix II – Solution in Java

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int row = 0;
        int col = matrix[0].length - 1;
        
        while(row <= matrix.length - 1 && col >= 0)
        {
            if(matrix[row][col] == target) return true;
            else if(matrix[row][col] < target) row++;
            else if(matrix[row][col] > target) col--;
        }
        return false;
    }
}

240. Search a 2D Matrix II – Solution in C++

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m = matrix.size(), n = m ? matrix[0].size() : 0, r = 0, c = n - 1;
        while (r < m && c >= 0) {
            if (matrix[r][c] == target) {
                return true;
            }
            matrix[r][c] > target ? c-- : r++;
        }
        return false;
    }
};

240. Search a 2D Matrix II – Solution in Python

def searchMatrix(matrix, target):
	m, n = len(matrix), len(matrix) and len(matrix[0])
	r, c = 0, n-1
	while r < m and c >= 0:
		if target > matrix[r][c]:
			r += 1
		elif target < matrix[r][c]:
			c -= 1
		else: return True
	return False

Note: This problem 240. Search a 2D Matrix II is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *