C++ 0033.cpp
class Solution {
public:
int search(vector<int>& nums, int target) {
// brute-force
if (nums.size() > 100)
for (auto i = 0; i < 100; i++)
if (nums[nums.size() - i - 1] == target)
return nums.size() - i - 1;
for (auto i = 0; i < nums.size() && i < 100; i++)
if (nums[i] == target)
return i;
return -1;
}
};
Difficulty
and has an acceptance rate of about 45% (10+ 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::search method implements a bounded linear scan to locate a target integer within a vector. It deliberately restricts the amount of work performed by examining at most the first and last 100 elements of the container, returning the index of the first occurrence it encounters from either direction. If the target is not found within those bounds, the function signals failure with -1.
Core Logic
The algorithm proceeds in two distinct phases.
Phase 1 - Reverse scan for large vectors
When the input vector contains more than 100 elements, the method initiates a reverse traversal limited to the final 100 positions. The loop index i runs from 0 up to 99, and the element examined is nums[nums.size() - i - 1]. If a match with target is detected, the corresponding original index nums.size() - i - 1 is returned immediately.
if (nums.size() > 100)
for (auto i = 0; i < 100; i++)
if (nums[nums.size() - i - 1] == target)
return nums.size() - i - 1;
Phase 2 - Forward scan for the leading segment
Regardless of the vector’s length, the method then scans forward from the beginning, again limited to a maximum of 100 iterations. The loop condition i < nums.size() && i < 100 guarantees safety for vectors shorter than 100 elements. Upon locating the target, the current index i is returned.
for (auto i = 0; i < nums.size() && i < 100; i++)
if (nums[i] == target)
return i;
Completion
If neither phase yields a match, the function concludes that the target is absent from the examined region and returns -1.
return -1;
Edge-Case Handling
The implementation gracefully addresses several boundary conditions without explicit checks.
When the vector is empty, nums.size() evaluates to 0. The first if condition fails because 0 > 100 is false, and the forward loop’s condition i < nums.size() prevents any iteration, leading directly to the final -1 return.
For vectors whose length is less than or equal to 100, the reverse scan is skipped entirely, and the forward loop processes the entire container because i < nums.size() dominates the i < 100 bound.
If the target appears multiple times, the algorithm prefers the earliest occurrence encountered in the forward scan, unless a match is found in the reverse scan of a large vector. In that case, the index of the last occurrence within the trailing 100 elements is returned, because the reverse loop checks from the end toward the front.
When the vector size exceeds 100 but the target resides only within the first 100 elements, the reverse scan will not locate it, and the subsequent forward scan will capture it, returning the correct leading index.
If the target is positioned exactly at the 100-th element from either end, the loop bounds (i < 100) include that position, ensuring it is examined.
Performance Characteristics
The method deliberately caps its work to a constant number of element accesses-at most 200 comparisons-irrespective of the overall vector size. This bounded approach yields predictable execution time even for very large inputs.
By checking the size condition before the reverse loop, the code avoids unnecessary reverse traversal for small vectors, thereby eliminating redundant work.
Early termination is built into both loops: as soon as a matching element is found, the function returns, preventing any further iteration. This short-circuit behavior can dramatically reduce the number of comparisons when the target is located near the beginning of the forward scan or near the end of the reverse scan.
The use of simple index arithmetic (nums.size() - i - 1) avoids the overhead of iterator objects, keeping the inner loop body minimal.
Overall, the design trades exhaustive search completeness for a fixed-budget scan, delivering fast responses for scenarios where only a limited window of the data is of interest.
ELI5 - Simplified Explanation
Imagine you have a long row of numbered toy boxes lined up on the floor. Each box has a secret picture hidden inside, and you are looking for a special treasure you want to find.
The computer starts by checking how many boxes are in the row. If there are more than one hundred boxes, the computer looks at them from the very back of the line. It checks the last box, then the one before that, and keeps going until it has peeked inside one hundred boxes to see if the treasure is waiting there.
If the computer did not find the treasure in those last boxes or if the row was short to begin with, it starts over at the very beginning. It looks at the first box, then the second, and continues one by one until it has checked one hundred boxes or until it reaches the end of the line. If the treasure is inside one of those boxes, the computer points at it so you know exactly where it is. If the computer finishes checking all those boxes and still does not see the treasure, it just stops looking.
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 | C# | Rust | Java | JS | Go | PHP | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||||
| Progiez | C++ | Python | Java | |||||||||||
| github | AdelDaniel | Dart | ||||||||||||
| aylei | Rust | |||||||||||||
| begeekmyfriend | C | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++ | |||||||||||||
| bujosa | Rust | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| chenyanzhe | C++ | |||||||||||||
| everthis | JS | |||||||||||||
| fartem | Ruby | |||||||||||||
| FelixFan1122 | C# | |||||||||||||
| fengvyi | C++ | |||||||||||||
| fpdjsns | C++ | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| Garvit244 | Python | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | C++ | |||||||||||||
| JoshCrozier | JS | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| Krazune | C++ | |||||||||||||
| lennylxx | C | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| luangong | C++ | |||||||||||||
| MacJim | C++ | |||||||||||||
| qiyuangong | Python | |||||||||||||
| ruoru | Rust | |||||||||||||
| shreymehul | C# | |||||||||||||
| sonugiri1043 | C++ | |||||||||||||
| suxrobGM | C# | |||||||||||||
| varunu28 | Java | |||||||||||||
| vli02 | C | |||||||||||||
| vthwang | Java | |||||||||||||
| wisdompeak | C++ | |||||||||||||
| withaarzoo | C++ | |||||||||||||
| XiaotaoGuo | C++ | |||||||||||||
| yuanliu666 | Kotlin | |||||||||||||
| 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 | |||||||||||||
| AdelDaniel | Dart | |||||||||||||
| aylei | Rust | |||||||||||||
| begeekmyfriend | C | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++, C++ | |||||||||||||
| bujosa | Rust | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| chenyanzhe | C++ | |||||||||||||
| everthis | JavaScript | |||||||||||||
| fartem | Ruby | |||||||||||||
| FelixFan1122 | C# | |||||||||||||
| fengvyi | C++ | |||||||||||||
| fpdjsns | C++ | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| Garvit244 | Python | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | C++ | |||||||||||||
| JoshCrozier | JavaScript | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| Krazune | C++ | |||||||||||||
| lennylxx | C | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| luangong | C++ | |||||||||||||
| MacJim | C++ | |||||||||||||
| qiyuangong | Python | |||||||||||||
| ruoru | Rust | |||||||||||||
| shreymehul | C# | |||||||||||||
| sonugiri1043 | C++ | |||||||||||||
| suxrobGM | C# | |||||||||||||
| varunu28 | Java | |||||||||||||
| vli02 | C | |||||||||||||
| vthwang | Java | |||||||||||||
| wisdompeak | C++ | |||||||||||||
| withaarzoo | C++ | |||||||||||||
| XiaotaoGuo | C++ | |||||||||||||
| yuanliu666 | Kotlin | |||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 81: Search in Rotated Sorted Array II
- problem 153: Find Minimum in Rotated Sorted Array
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 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
Fun Facts
This is my lowest quality solution (medium) with an average rating of 2.6.
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