C++ 0074.cpp
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
for (auto& r : matrix)
{
if (target < r.front())
return false;
if (target > r.back())
continue;
return binary_search(r.begin(), r.end(), target);
}
return false;
}
};
Difficulty
and has an acceptance rate of about 54% (5+ million submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- 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 solves the classic “search a value in a 2-D matrix” problem. It treats each row as an independent sorted array and iterates through the rows to locate the one that could contain the target. Once a candidate row is found, it delegates the actual lookup to the standard library’s binary search routine. The algorithm returns a boolean indicating whether the target exists in the matrix.
Key Steps
Row-wise filtering
for (auto& r : matrix)
{
if (target < r.front())
return false;
if (target > r.back())
continue;
The loop walks through each row r. The first conditional checks whether the target is smaller than the smallest element of the current row (r.front()). Because rows are sorted in ascending order, a smaller target cannot appear in any later row, so the function returns false immediately. The second conditional discards rows whose largest element (r.back()) is still smaller than the target, allowing the loop to continue to the next row.
Binary search within the candidate row
return binary_search(r.begin(), r.end(), target);
}
When the target lies between the first and last elements of a row, the code invokes std::binary_search. This standard algorithm performs a logarithmic search over the row’s range, yielding a true result if the target is present and false otherwise. The return statement exits the function as soon as the appropriate row has been examined.
Exhaustive failure case
return false;
If the loop finishes without finding a suitable row (for example, when the matrix is empty or all rows are exhausted), the function reaches this final statement and reports that the target is absent.
Edge Cases Handled
When the matrix contains no rows, the range-based for loop executes zero times, and the function falls through to the final return false;. This correctly reports that no element can be found in an empty structure.
If a row itself is empty, calling r.front() or r.back() would be undefined. The code assumes that every row contains at least one element, which aligns with the typical problem constraints where each sub-vector is non-empty.
The early-exit condition if (target < r.front()) return false; also covers the scenario where the target is smaller than every element in the matrix. Because rows are processed in order, the first row’s smallest element provides a global lower bound; encountering a smaller target triggers an immediate false without scanning the remaining rows.
Conversely, when the target exceeds the largest element of the last row, the loop iterates through all rows, each time hitting if (target > r.back()) continue;. After the loop ends, the final return false; correctly indicates the target’s absence.
Performance Optimizations
The algorithm leverages two natural ordering properties of the matrix: each row is sorted, and rows themselves are ordered by their first elements. By checking the front and back values of each row before invoking a full search, the code eliminates unnecessary binary searches on rows that cannot possibly contain the target. This reduces the number of expensive logarithmic operations to at most one per execution.
Using std::binary_search provides a highly tuned implementation that benefits from in-line optimizations and branch prediction friendly code paths, ensuring the inner search runs efficiently.
The early termination when target < r.front() prevents the algorithm from traversing the remainder of the matrix once it is clear that the target cannot appear later, saving time especially for large matrices where the target is smaller than the global minimum.
Overall, the combination of row-level bounds checking and a single binary search yields a solution that scales well with both the number of rows and the length of each row, while keeping the code concise and leveraging the standard library for optimal low-level performance.
ELI5 - Simplified Explanation
Imagine you have a big box filled with smaller boxes, and each one of those smaller boxes is packed with numbers that are all lined up neatly from smallest to largest. You are trying to find one specific secret number hidden somewhere deep inside. This code starts by looking at each little box one by one. First, it checks the very first number in the box to see if the secret number is too small to be hiding there. Then, it checks the very last number in the box to see if the secret number is too big to be hiding there. If the secret number fits somewhere between those two spots, the code stops looking at the outside of the boxes and starts searching very quickly inside that specific one to find your secret number. If it finds it, you know it is there. If it checks every little box and still has not found the secret number, then the number just is not in the big box at all.
Code Quality
Complexity Analysis
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 | Rust | JS | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| bujosa | Rust | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| bujosa | Rust | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 240: Search a 2D Matrix II
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
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