Problem 219

Abstract / Summary

Check if any two numbers in an array are the same and their positions differ by no more than a given value.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
18 lines | 427 bytes | submitted August 9, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 52% (3+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Sliding Window
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.19 | σ = 0.61

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
54 links | 37 authors | 13 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Contains Duplicate II - Leetcode 219 - Python'
NeetCodeIO 6 mins
Contains Duplicate II - Leetcode 219 - Python
YouTube video 'Contains Duplicate II (Sliding Window) -(Airbnb, Palantir Technologies): Explanation ➕ Live Coding'
codestorywithMIK 17 mins
Contains Duplicate II (Sliding Window) -(Airbnb, Palantir Technologies): Explanation ➕ Live Coding
YouTube video '219. Contains Duplicate II | LEETCODE EASY'
code Explainer 8 mins
219. Contains Duplicate II | LEETCODE EASY
YouTube video 'Contains Duplicate II -(Airbnb, Palantir Technologies): Explanation ➕ Live Coding 🧑🏻‍💻'
codestorywithMIK 12 mins
Contains Duplicate II -(Airbnb, Palantir Technologies): Explanation ➕ Live Coding 🧑🏻‍💻
YouTube video '219. Contains Duplicate ii || Java || Leetcode || Hindi'
Coding Sphere 7 mins
219. Contains Duplicate ii || Java || Leetcode || Hindi
YouTube video 'Leetcode | 219. Contains Duplicate II | Easy | Java Solution'
Developer Docs 7 mins
Leetcode | 219. Contains Duplicate II | Easy | Java Solution
YouTube video 'LeetCode 219 | Contains Duplicate II'
Engineering Digest 11 mins
LeetCode 219 | Contains Duplicate II
YouTube video 'Contains Duplicate II  LeetCode 219 | Intuitive Explanation + Code'
CodingNinja 14 mins
Contains Duplicate II LeetCode 219 | Intuitive Explanation + Code
YouTube video 'LeetCode 217 & 219: Contains Duplicate I & II - Interview Prep Ep 46'
Fisher Coder 19 mins
LeetCode 217 & 219: Contains Duplicate I & II - Interview Prep Ep 46
YouTube video 'Contains Duplicate II: 219 - Array interview question @ google, apple, amazon, meta, microsoft, uber'
Destination FAANG 13 mins
Contains Duplicate II: 219 - Array interview question @ google, apple, amazon, meta, microsoft, uber
YouTube video 'Contains Duplicate II - LeetCode 219 - Python #leetcode'
Deepti Talesra 6 mins
Contains Duplicate II - LeetCode 219 - Python #leetcode
YouTube video 'Contains Duplicate II | LeetCode 219 | Java 10ms solution | @LearnOverflow'
Learn Overflow 15 mins
Contains Duplicate II | LeetCode 219 | Java 10ms solution | @LearnOverflow
YouTube video 'Contains Duplicate II | Telugu Coding Tutorial | Brute Force, Hash Table & Sliding Window | srkcodes'
Srk Codes 12 mins
Contains Duplicate II | Telugu Coding Tutorial | Brute Force, Hash Table & Sliding Window | srkcodes
YouTube video 'Daily Leetcode #934: Oct 21, 2022 - 219. Contains Duplicate II'
Programming Live with Larry 4 mins
Daily Leetcode #934: Oct 21, 2022 - 219. Contains Duplicate II
YouTube video 'LeetCode 219 | Contains Duplicate II | HashMap | HashSet | Java'
Sleepy Cracker 4 mins
LeetCode 219 | Contains Duplicate II | HashMap | HashSet | Java
YouTube video 'LeetCode 219 | Contains Duplicate II | C# Solution | Sliding Window with HashSet |'
Code Scribbler 7 mins
LeetCode 219 | Contains Duplicate II | C# Solution | Sliding Window with HashSet |
YouTube video '219. Contains Duplicate II | Leetcode | Python'
Abdullah Arshed 6 mins
219. Contains Duplicate II | Leetcode | Python
YouTube video 'Leetcode | 219. Contains Duplicate II | Easy | Javascript'
Software Interviews Prep 6 mins
Leetcode | 219. Contains Duplicate II | Easy | Javascript
YouTube video '219. Contains Duplicate II (LeetCode)'
hakunamatasq 3 mins
219. Contains Duplicate II (LeetCode)
YouTube video 'Leetcode 219: Contains Duplicate II'
Algorithms Casts 5 mins
Leetcode 219: Contains Duplicate II
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

9 easy 2 medium 16 hard
28 solutions   August 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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