Leetcode 74 - Search a 2D Matrix

post-thumb

Advance your Tech Career to new heights with Personalized Coaching from industry Experts at top companies.

Meet Your MAANG Coach Now

Understanding the problem

The problem statement on LeetCode reads as follows:

Write an efficient algorithm that searches for a value in an m x n 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,50]], target = 3 Output: true

Example 2:

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

Plan your solution

One way to solve this problem is to use a binary search algorithm. Since the rows of the matrix are sorted in increasing order, we can use binary search to find the row that the target value is in. Once we find the row, we can use binary search again to find the target value within that row.

Implement your solution

Now that we have a plan, let’s implement it in Python.

def searchMatrix(matrix, target):
    # Edge case: if the matrix is empty, return False
    if not matrix:
        return False

    # Find the row that the target value is in using binary search
    left = 0
    right = len(matrix) - 1
    while left <= right:
        mid = (left + right) // 2
        if matrix[mid][0] <= target <= matrix[mid][-1]:
            row = mid
            break
        elif matrix[mid][0] > target:
            right = mid - 1
        else:
            left = mid + 1
    else:
        return False

    # Find the target value within the row using binary search
    left = 0
    right = len(matrix[row]) - 1
    while left <= right:
        mid = (left + right) // 2
        if matrix[row][mid] == target:
            return True
        elif matrix[row][mid] > target:
            right = mid - 1
        else:
            left = mid + 1

    return False

Test your solution

Testing is an important step in the software development process, as it helps ensure that your code is correct and works as intended. In the case of the “Search a 2D Matrix” problem, we can test our solution by running a series of test cases that cover different scenarios and edge cases.

For example, we can test our solution with an empty matrix, a matrix with only one element, a matrix with multiple elements but no target value, and a matrix with multiple elements including the target value. We can also test our solution with matrices of different sizes and with different types of elements (e.g. integers, strings, etc.). By running a variety of test cases, we can gain confidence that our solution is correct and will work for all inputs.

Advance your Tech Career to new heights with Personalized Coaching from industry Experts at top companies.

Meet Your MAANG Coach Now

Related:

comments powered by Disqus