↓Skip to main content
  1. LeetCode/

LeetCode 240: Search a 2D Matrix II

·2 mins· ·
LeetCode Medium Array Binary-Search Divide-and-Conquer Matrix
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-12

  • Submissions: Accepted ×2 → Runtime Error ×2 → Accepted → Runtime Error → Accepted → Wrong Answer ×2 → Accepted

Approach
#

Rows increase left to right and columns top to bottom, but rows do not continue each other, so no flattening. Start at the top-right (Binary Search):

  • Current value larger than the target: everything below in this column is larger too, so go left.
  • Smaller: everything to the left in this row is smaller, so go down.

Each step eliminates a column or a row, at most m + n steps.

My Attempts
#

My first accepted version in 2022 began with if not matrix or not target: return False, which returns False whenever target is 0; the tests simply missed it. A 2026 rewrite walked right as far as possible and then straight down, which skips answers: [[1, 1, 3], [4, 7, 8]], target = 7 should be True; it returned False.

Solution
#

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        i, j = 0, len(matrix[0]) - 1
        while i < len(matrix) and j >= 0:
            v = matrix[i][j]
            if v == target:
                return True
            if v > target:
                j -= 1
            else:
                i += 1
        return False

Complexity
#

Time O(m + n), space O(1).

Mistakes to Avoid
#

  • Start at the top-right (or bottom-left), where one direction increases and the other decreases.
  • target can be 0; do not test it with not target.

Interview Explanation
#

From the top-right I go left when larger and down when smaller, eliminating a column or row each step; leaving the grid means absent. Time O(m + n).

Related

LeetCode 74: Search a 2D Matrix
·2 mins
LeetCode Medium Array Binary-Search Matrix
LeetCode 74 note: each row continues the previous one in sorted order, so binary search it as a 1-D array of length m × n, mapping mid to (mid // n, mid % n)
LeetCode 162: Find Peak Element
·2 mins
LeetCode Medium Array Binary-Search
LeetCode 162 note: nums[mid] < nums[mid + 1] guarantees a peak to the right (rising until the edge at worst), otherwise one at or left of mid
LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal
·1 min
LeetCode Medium Array Hash-Table Divide-and-Conquer Tree
LeetCode 106 note: the last post-order value is the root; taking roots from the end of the post-order, build the right subtree before the left
LeetCode 48: Rotate Image
·2 mins
LeetCode Medium Array Math Matrix
LeetCode 48 note: rotating 90 degrees clockwise is a transpose followed by reversing each row, both in place
LeetCode 417: Pacific Atlantic Water Flow
·3 mins
LeetCode Medium Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 417 note: walk inward from each ocean’s shore to cells no lower than the current one; cells reached from both oceans are the answer
LeetCode 105: Construct Binary Tree from Preorder and Inorder Traversal
·2 mins
LeetCode Medium Array Hash-Table Divide-and-Conquer Tree
LeetCode 105 note: the first pre-order value is the root, and its position in the in-order tells the left subtree’s size; look positions up in a dictionary for O(n)