C++ 0034.cpp
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
auto one = lower_bound(nums.begin(), nums.end(), target);
auto two = lower_bound(one, nums.end(), target + 1);
if (one == nums.end() || *one != target)
return { -1, -1 };
return { int(one - nums.begin()), int(two - nums.begin()) - 1 };
}
};
Difficulty
and has an acceptance rate of about 49% (7+ 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 presented Solution class implements a method searchRange that receives a sorted integer vector nums and an integer target. Its purpose is to locate the first and last indices where target appears in the vector. If the target does not exist, the method returns {-1, -1}. The implementation relies on the standard library function lower_bound to perform binary searches, thereby achieving an efficient solution for the problem.
Key Steps
The algorithm proceeds in three distinct stages.
The first stage identifies the leftmost occurrence of target by invoking lower_bound on the entire range of the vector.
auto one = lower_bound(nums.begin(), nums.end(), target);
The second stage finds the position just past the rightmost occurrence of target. It starts the search from the iterator returned by the first stage, which narrows the search space and avoids re-examining elements that are already known to be less than target.
auto two = lower_bound(one, nums.end(), target + 1);
The third stage validates whether the target was actually found. If the iterator one points to the end of the vector or the dereferenced value does not equal target, the method returns the sentinel pair {-1, -1}. Otherwise, it computes the integer indices by subtracting the beginning iterator from one and two, adjusting the right index by subtracting one to obtain the last valid position.
if (one == nums.end() || *one != target)
return { -1, -1 };
return { int(one - nums.begin()), int(two - nums.begin()) - 1 };
Edge Cases Handled
When the input vector is empty, lower_bound immediately yields nums.end(). The subsequent check one == nums.end() triggers the early return of {-1, -1}, correctly indicating the absence of any target.
If the target value is smaller than all elements in the vector, the first lower_bound call returns an iterator to the first element, but the condition *one != target fails, leading again to the sentinel result.
When the target is larger than every element, lower_bound returns nums.end(). The same early-return condition captures this scenario.
For vectors that contain multiple consecutive occurrences of the target, the first lower_bound finds the first occurrence, while the second lower_bound-searching for target + 1-lands on the element immediately after the last occurrence. Subtracting one from that position yields the correct index of the final target element.
If the target appears exactly once, both one and two will point to the same element and the element after it, respectively, resulting in a range where the start and end indices are identical, which the method returns accurately.
Performance Optimizations
The implementation leverages the logarithmic search behavior of lower_bound, which performs a binary search on the sorted range. By calling lower_bound twice, the algorithm maintains an overall logarithmic time profile while avoiding a full linear scan.
Starting the second lower_bound from the iterator one rather than from nums.begin() reduces the number of comparisons needed to locate the upper bound, because all elements before one are already known to be less than target.
The use of iterator arithmetic (one - nums.begin()) provides constant-time index calculation without additional loops or auxiliary data structures. Casting the result to int ensures the return type matches the expected vector of integers.
Overall, the code achieves a compact and efficient solution by combining standard library facilities with careful iterator management, resulting in minimal overhead and clear expression of the intended algorithmic steps.
ELI5 - Simplified Explanation
Imagine you have a long row of numbered toy blocks lined up from smallest to biggest. You are looking for all the blocks that have a specific number written on them. Since the blocks are already sorted, you do not have to pick up every single one to check.
The code works like a smart scout who starts at the beginning of the row. The first part, called lower bound, sends the scout to find the very first block that matches the number you want. Once the scout finds that spot, it remembers exactly where it is.
Then, the code sends the scout back out again to find the spot where the numbers would change into something bigger than your target. This helps the scout see where the group of your matching blocks ends.
If the scout realizes that the first spot is actually at the very end of the row, or if the number there is not the one you were looking for at all, it knows those blocks are missing. Otherwise, it uses the starting spot and the ending spot to tell you the sandwich of blocks that hold your favorite number.
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 | C# | Rust | JS | Go | PHP | TS | |||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | Go | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lennylxx | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| 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, PHP, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | Go | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lennylxx | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
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 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 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