Problem 240

Abstract / Summary

Search a sorted rows and columns matrix for a value efficiently without using specific algorithms.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0240.py

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        left  = 0
        right = len(matrix[0])
        for y in range(len(matrix)):
            if matrix[y][-1] < target:
                continue

            pos = bisect_right(matrix[y], target, left, right)
            print(pos, y)
            if pos == 0 and matrix[y][0] > target:
                return False
            if pos > 0 and matrix[y][pos - 1] == target:
                return True

            right = pos

        return False
18 lines | 560 bytes | submitted September 7, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 58% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Divide And Conquer
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a method searchMatrix that determines whether a given integer target exists within a two-dimensional list matrix. The matrix is assumed to be sorted row-wise in non-decreasing order, and each row’s last element is not smaller than the first element of the next row. The algorithm proceeds row by row, narrowing the search interval based on binary search results, and stops early when the target cannot possibly appear in the remaining rows.

Key Steps

The method begins by establishing the initial search bounds for each row. The left bound is fixed at zero, while the right bound is set to the length of the first row, representing the exclusive upper index for binary search.

left  = 0
right = len(matrix[0])

A loop iterates over the row index y. For each row, the algorithm first checks whether the row’s greatest element is smaller than the target. If that condition holds, the row is skipped because the target cannot be present in that row or any preceding rows.

for y in range(len(matrix)):
    if matrix[y][-1] < target:
        continue

When a row passes the preliminary check, a binary search is performed using bisect_right. The call restricts the search to the current interval [left, right). The returned position pos indicates the insertion point for target to maintain sorted order, i.e., the index of the first element greater than target.

pos = bisect_right(matrix[y], target, left, right)
print(pos, y)

Two immediate conditions are evaluated after the binary search. The first condition handles the scenario where the insertion point is at the very beginning of the row and the first element exceeds the target. In that case, the algorithm concludes that the target cannot appear in any subsequent rows and returns False.

if pos == 0 and matrix[y][0] > target:
    return False

The second condition checks whether the element immediately preceding the insertion point matches the target. If it does, the method returns True, indicating a successful find.

if pos > 0 and matrix[y][pos - 1] == target:
    return True

If neither early-exit condition is triggered, the right bound for subsequent rows is updated to the current insertion point. This adjustment narrows the search window for the next iteration, ensuring that later rows are examined only up to the point where the target could still possibly appear.

right = pos

After all rows have been processed without locating the target, the method returns False.

return False

Edge Cases Handled

The algorithm explicitly addresses the case where a row’s last element is smaller than the target, allowing it to skip that row entirely. This prevents unnecessary binary searches on rows that cannot contain the target.

When the binary search yields an insertion point of zero, the code checks whether the first element of the row is already larger than the target. If so, it deduces that the target is smaller than every element in the current and all following rows, leading to an immediate False return.

The condition pos > 0 and matrix[y][pos - 1] == target safely handles the situation where the target equals the first element of a row, because pos would be at least one in that case, allowing the equality check without risking an out-of-range index.

By updating right to pos after each row, the method ensures that subsequent binary searches never examine indices beyond the last possible location of the target, even when rows have varying lengths or when the target lies near the beginning of the matrix.

Performance Optimizations

The early-skip check if matrix[y][-1] < target: continue eliminates entire rows from consideration when their maximum value is insufficient, reducing the number of binary searches performed.

Restricting the binary search range with the left and right parameters focuses the search on the smallest feasible segment of each row. As right monotonically decreases or stays the same across rows, the algorithm avoids re-examining elements that have already been proven irrelevant, effectively pruning the search space.

The use of bisect_right from the standard library provides a highly optimized binary search implementation written in C, offering faster execution than a pure Python loop.

By returning immediately upon finding the target or upon determining that the target cannot exist in any remaining rows, the method avoids unnecessary iteration, achieving early termination in favorable scenarios.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big grid made of squares, where each square holds a secret number. These numbers are all lined up in order from smallest to biggest, just like how books might be lined up on a shelf. The goal is to play a game of hide and seek to find one special number that is hiding somewhere in this grid.

To start, the computer looks at each row of the grid one by one. If the numbers in a row are all too small, the computer skipped that row entirely, like jumping over a puddle to reach the next part of the path. Once the computer finds a row that might have the special number, it uses a clever trick to scan through those squares very quickly instead of checking every single one. This is similar to peeking at the middle of a book to see if the page you want is near the front or the back.

The computer keeps track of where it has looked by remembering a left boundary and a right boundary. Every time it makes a move, it makes those boundaries tighter so it knows exactly where the number could be hiding. If it spots the number, the game ends because the secret friend was found. If the computer finishes looking through all the rows and cannot find the number, it simply stops, which means the number was not playing hide and seek in the grid today.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.56 | σ = 1.55

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# JS Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
fsq Python
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel Java
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
fsq Python
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel Java
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
53 links | 36 authors | 10 languages

Videos

12 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

30 easy 12 medium
43 solutions   September 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality