C++ 0704.cpp
class Solution {
public:
int search(vector<int>& nums, int target) {
auto i = lower_bound(nums.begin(), nums.end(), target);
if (i == nums.end())
return -1;
if (*i == target)
return i - nums.begin();
return -1;
}
};
Difficulty
and has an acceptance rate of about 61% (6+ million submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
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 single public method search. The method receives a reference to a vector<int> named nums and an integer target. Its purpose is to locate the index of target within the sorted vector, returning -1 when the value is absent. The algorithm leverages the standard library function lower_bound to perform a binary search, thereby achieving logarithmic search time on a sorted range.
Key Steps
The first significant operation is the invocation of lower_bound:
auto i = lower_bound(nums.begin(), nums.end(), target);
lower_bound returns an iterator pointing to the first element that is not less than target. This iterator may point to the exact match, to a larger element, or to the end of the container if all elements are smaller than target.
The next step checks whether the iterator has reached the end of the vector:
if (i == nums.end())
return -1;
If the iterator equals nums.end(), it indicates that every element in the vector is smaller than target, and consequently the target cannot be present.
When the iterator is not at the end, the code verifies that the dereferenced value matches the target:
if (*i == target)
return i - nums.begin();
If the condition holds, the method computes the zero-based index by subtracting nums.begin() from the iterator, which yields the distance between the two iterators.
If the dereferenced value differs from target, the method concludes that the target is absent and returns -1:
return -1;
Edge Cases Handled
The algorithm gracefully handles an empty input vector. In that scenario, lower_bound immediately returns nums.end(), triggering the early exit that returns -1. This avoids any dereferencing of an invalid iterator.
When the target is smaller than the smallest element in the vector, lower_bound yields an iterator to the first element. The subsequent equality check fails, and the method returns -1, correctly indicating absence.
If the target is larger than the largest element, lower_bound returns nums.end(). The early end-of-range check captures this case, again returning -1.
When the target appears multiple times, lower_bound points to the first occurrence because it finds the first element not less than the target. The index calculation therefore returns the index of the earliest matching element, which aligns with typical expectations for a search routine.
Performance Optimizations
The core optimization stems from the use of lower_bound, a standard algorithm that implements binary search internally. By delegating the search to this library routine, the code benefits from a highly tuned implementation that minimizes branch mispredictions and leverages iterator arithmetic efficiently.
The method avoids any explicit loops or additional data structures, keeping the memory footprint minimal. The distance calculation i - nums.begin() is performed using iterator subtraction, which for random-access iterators (as provided by vector) is a constant-time operation.
Early termination is achieved through the if (i == nums.end()) guard. This prevents unnecessary dereferencing when the target lies beyond the range of the container, saving a potential comparison.
Overall, the combination of a standard binary search, constant-time index computation, and early exit conditions results in a concise and performant solution for locating an element in a sorted integer vector.
ELI5 - Simplified Explanation
Imagine you have a long line of numbered toy blocks all arranged in order from smallest to biggest. You want to find one specific block with a certain number written on it.
The code acts like a very fast helper who starts by looking at the middle of the line to guess where that block might be hiding. Because the blocks are already in order, the helper can quickly skip over big sections that are too small or too large, which saves a lot of time.
The first part of the code asks the helper to find the first spot where the target block could live. If the helper reaches the very end of the line and still has not found the target, it tells you that the block is missing. If the helper stops and sees that the block at that spot is exactly the one you were looking for, it tells you the position number of that block in the line so you can go pick it up. If the helper stops and the block is not the right number, it lets you know the block is not there.
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++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | Python | |||||||||
| leetcode.ca | C++ | Java | Rust | C# | Python | JS | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | AdelDaniel | Dart | ||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| bujosa | Rust | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| Dijkstra-Edu | C++ | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fpdjsns | C++ | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| yuanliu666 | Java | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| AdelDaniel | Dart | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| bujosa | Rust | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| Dijkstra-Edu | C++ | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fpdjsns | C++ | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| yuanliu666 | Java |
Videos
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 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 74: Search a 2D Matrix
- 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