Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Search a 2D Matrix II

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "240" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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

Explanation

Here's a solution to efficiently search for a target value in a sorted matrix with the given properties:

  • Start at the top-right corner: Begin the search from the element at matrix[0][n-1]. This position allows us to simultaneously eliminate either a row or a column in each comparison.
  • Comparison and Movement: Compare the current element with the target.
    • If the current element is equal to the target, return true.
    • If the current element is greater than the target, it means all elements in the current column below this element are also greater than the target (due to column-wise sorting). So, move one column to the left.
    • If the current element is smaller than the target, it means all elements in the current row to the left of this element are also smaller than the target (due to row-wise sorting). So, move one row down.
  • Out-of-bounds Check: Continue these comparisons and movements until either the target is found or the search goes out of bounds (i.e., the row index becomes greater than or equal to m, or the column index becomes less than 0). If the target is not found after the search completes, return false.

  • Runtime Complexity: O(m + n), where 'm' is the number of rows and 'n' is the number of columns.

  • Storage Complexity: O(1) (constant).

Code

    def searchMatrix(matrix, target):
    """
    Searches for a target value in a sorted matrix.

    Args:
        matrix: A list of lists of integers, where each row and column is sorted in ascending order.
        target: The integer to search for.

    Returns:
        True if the target is found in the matrix, False otherwise.
    """
    if not matrix or not matrix[0]:
        return False

    m = len(matrix)
    n = len(matrix[0])
    row = 0
    col = n - 1

    while row < m and col >= 0:
        if matrix[row][col] == target:
            return True
        elif matrix[row][col] > target:
            col -= 1
        else:
            row += 1

    return False

More from this blog

C

Chatmagic blog

2894 posts