C++ 0219.cpp
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> last;
for (int i = 0; i < nums.size(); i++)
{
auto current = nums[i];
if (last.count(current) > 0)
if (i - last[current] <= k)
return true;
last[current] = i;
}
return false;
}
};
Difficulty
and has an acceptance rate of about 52% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Sliding Window
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 “contains nearby duplicate” problem. It receives an integer vector nums and an integer k, and determines whether any two equal elements exist whose indices differ by at most k. The algorithm walks through the array once, maintaining a hash map that records the most recent index at which each value was seen. When a value reappears, the distance to its previous occurrence is checked against k. If the distance satisfies the constraint, the function returns true; otherwise the scan continues. If the end of the array is reached without finding a qualifying pair, the function returns false.
Key Steps
Initialization of the hash map
The method begins by declaring an unordered map named last that maps integer values to their latest index.
unordered_map<int, int> last;
This container provides constant-time average look-ups and updates, which is essential for the linear-time behavior of the algorithm.
Iteration over the input vector
A standard for loop iterates from the first element to the last, using the index variable i.
for (int i = 0; i < nums.size(); i++)
{
auto current = nums[i];
// ...
}
The loop variable i serves both as the current position and as the value to be stored in the map when a new occurrence is processed.
Detection of a previous occurrence
Inside the loop, the code checks whether the current element has been seen before by querying the map with count. The condition last.count(current) > 0 evaluates to true only when the element exists as a key.
if (last.count(current) > 0)
if (i - last[current] <= k)
return true;
If a prior occurrence exists, the distance between the current index i and the stored index last[current] is computed. When this distance does not exceed k, the function immediately returns true, indicating that a qualifying duplicate pair has been found.
Updating the most recent index
Regardless of whether a duplicate was found, the map entry for the current value is refreshed with the current index. This ensures that the algorithm always compares against the closest preceding occurrence.
last[current] = i;
By overwriting the previous index, the method guarantees that later checks use the smallest possible distance for any subsequent duplicate of the same value.
Final return statement
If the loop completes without triggering the early return, the method concludes that no suitable duplicate pair exists and returns false.
return false;
Edge Cases Handled
The code naturally accommodates an empty input vector because the loop body is never entered, leading directly to the final false return. When k is zero, the distance check i - last[current] <= k can only succeed if two identical elements occupy the same index, which is impossible; therefore the function correctly returns false. The algorithm also handles vectors containing a single element, as the map will contain at most one entry and the distance condition can never be satisfied. Negative values in nums pose no problem because the unordered map keys are signed integers, and the hash function works uniformly for the full integer range.
Performance Optimizations Observed
The primary optimization stems from the use of an unordered_map to store the most recent index for each distinct value. This choice yields average constant-time operations for both existence checks (count) and value retrieval (operator[]). By updating the map entry on every iteration, the algorithm avoids the need to store a list of all previous indices for each value, thereby limiting memory usage to at most one entry per distinct element.
The early return on finding a qualifying pair prevents unnecessary processing of the remaining elements, which can dramatically reduce runtime on inputs where a valid duplicate appears early. The loop runs in a single pass, eliminating any nested iteration that could increase the computational cost.
Overall, the implementation achieves a linear traversal of the input with minimal auxiliary storage, delivering efficient performance for large vectors while correctly handling all relevant edge conditions.
ELI5 - Simplified Explanation
Imagine you have a long row of numbered toy blocks. Your goal is to find if there are two blocks with the same number that are sitting close to each other.
To help with this, you keep a little notebook. As you walk down the row of blocks, you pick up each block one by one and look at the number written on it. You check your notebook to see if you have seen this same number before.
If the number is not in your notebook, you write down the number and mark exactly where you found it.
If you see that the number is already in your notebook, you peek at the spot you wrote down earlier. You check if the old spot and the new spot are close enough together, based on the gap allowed. If they are close, then you have found what you were looking for. If not, you just cross out the old spot in your notebook and write down the new spot so that if you ever see that number again, you will remember the most recent time you saw it.
You keep doing this until you get to the very end of the row of blocks. If you finish looking at every single block and never find two that are the same and close enough together, then you know there are no hidden pairs.
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 | Python | C++ | Java | TS | |||||||||
| WalkCCC | Python | C++ | Java | |||||||||||
| leetcode.ca | Python | C++ | Java | JS | C# | Go | PHP | TS | ||||||
| LeetcodeHelp | Python | C++ | Java | |||||||||||
| MemoryLimitExceeded | Python | C++ | ||||||||||||
| Progiez | Python | C++ | Java | |||||||||||
| github | AdelDaniel | Dart | ||||||||||||
| aylei | Rust | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++ | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| chenyanzhe | C++ | |||||||||||||
| DimitrisJim | JS | |||||||||||||
| everthis | JS | |||||||||||||
| fartem | Ruby | |||||||||||||
| FelixFan1122 | Java | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | Python | |||||||||||||
| JoshCrozier | JS | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| lennylxx | C | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| muhammadfarhankt | Go | |||||||||||||
| pruthvikp | Python | |||||||||||||
| qiyuangong | Java | |||||||||||||
| ruoru | Rust | |||||||||||||
| shreymehul | C# | |||||||||||||
| suxrobGM | C# | |||||||||||||
| varunu28 | Java | |||||||||||||
| vli02 | C | |||||||||||||
| vthwang | Java | |||||||||||||
| yuanliu666 | Kotlin | |||||||||||||
| YuriSpiridonov | Python | |||||||||||||
| zfang399 | C++ | |||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||||
| WalkCCC | C++, Python, Java | |||||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, PHP, Python, TypeScript | |||||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||||
| Progiez | C++, Java, Python | |||||||||||||
| AdelDaniel | Dart | |||||||||||||
| aylei | Rust | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++, C++ | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| chenyanzhe | C++ | |||||||||||||
| DimitrisJim | JavaScript | |||||||||||||
| everthis | JavaScript | |||||||||||||
| fartem | Ruby | |||||||||||||
| FelixFan1122 | Java | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | Python | |||||||||||||
| JoshCrozier | JavaScript | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| lennylxx | C | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| muhammadfarhankt | Go | |||||||||||||
| pruthvikp | Python | |||||||||||||
| qiyuangong | Java | |||||||||||||
| ruoru | Rust | |||||||||||||
| shreymehul | C# | |||||||||||||
| suxrobGM | C# | |||||||||||||
| varunu28 | Java | |||||||||||||
| vli02 | C | |||||||||||||
| vthwang | Java | |||||||||||||
| yuanliu666 | Kotlin | |||||||||||||
| YuriSpiridonov | Python | |||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 217: Contains Duplicate
- problem 220: Contains Duplicate III
- problem 359: Logger Rate Limiter
Solved On The Same Day
- problem 125: Valid Palindrome
- problem 191: Number of 1 Bits
- problem 202: Happy Number
- problem 217: Contains Duplicate
- problem 290: Word Pattern
- problem 383: Ransom Note
- problem 392: Is Subsequence
- problem 1047: Remove All Adjacent Duplicates In String
- problem 1089: Duplicate Zeros
- problem 151: Reverse Words in a String
- problem 187: Repeated DNA Sequences
- problem 51: N-Queens
- problem 52: N-Queens II
- problem 60: Permutation Sequence
- problem 68: Text Justification
- problem 76: Minimum Window Substring
- problem 135: Candy
- problem 140: Word Break II
- problem 220: Contains Duplicate III
- problem 239: Sliding Window Maximum
- problem 352: Data Stream as Disjoint Intervals
- problem 502: IPO
- problem 895: Maximum Frequency Stack
- problem 982: Triples with Bitwise AND Equal To Zero
- problem 995: Minimum Number of K Consecutive Bit Flips
- problem 996: Number of Squareful Arrays
- problem 2136: Earliest Possible Day of Full Bloom
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