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
Difficulty
and has an acceptance rate of about 58% (2+ million submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Divide And Conquer
- Matrix
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 74: Search a 2D Matrix
Solved On The Same Day
- problem 415: Add Strings
- problem 463: Island Perimeter
- problem 541: Reverse String II
- problem 1211: Queries Quality and Percentage
- problem 1251: Average Selling Price
- problem 1280: Students and Examinations
- problem 1327: List the Products Ordered in a Period
- problem 1378: Replace Employee ID With The Unique Identifier
- problem 1407: Top Travellers
- problem 1484: Group Sold Products By The Date
- problem 1517: Find Users With Valid E-Mails
- problem 1527: Patients With a Condition
- problem 1581: Customer Who Visited but Did Not Make Any Transactions
- problem 1587: Bank Account Summary II
- problem 1633: Percentage of Users Attended a Contest
- problem 1661: Average Time of Process per Machine
- problem 1667: Fix Names in a Table
- problem 1683: Invalid Tweets
- problem 1693: Daily Leads and Partners
- problem 1729: Find Followers Count
- problem 1731: The Number of Employees Which Report to Each Employee
- problem 1741: Find Total Time Spent by Each Employee
- problem 1757: Recyclable and Low Fat Products
- problem 1789: Primary Department for Each Employee
- problem 1795: Rearrange Products Table
- problem 1873: Calculate Special Bonus
- problem 1890: The Latest Login in 2020
- problem 1965: Employees With Missing Information
- problem 1978: Employees Whose Manager Left the Company
- problem 2356: Number of Unique Subjects Taught by Each Teacher
- problem 166: Fraction to Recurring Decimal
- problem 223: Rectangle Area
- problem 318: Maximum Product of Word Lengths
- problem 357: Count Numbers with Unique Digits
- problem 394: Decode String
- problem 1158: Market Analysis I
- problem 1341: Movie Rating
- problem 1492: The kth Factor of n
- problem 1498: Number of Subsequences That Satisfy the Given Sum Condition
- problem 1907: Count Salary Categories
- problem 1934: Confirmation Rate
- problem 2405: Optimal Partition of String
Extra
- 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