← Home

219. Contains Duplicate II

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
sliding windowC++Markdown
219

This is one of those problems where the clean idea matters more than the amount of code. For 219. Contains Duplicate II, the solution in this repository is mainly a sliding window solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: sliding window.

The notes already sitting in the source point us in the right direction:

  • TLE

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are containsNearbyDuplicate.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//TLE
02class Solution {
03public:
04    bool containsNearbyDuplicate(vector<int>& nums, int k) {
05        for(int i = 0; i < nums.size(); i++){
06            for(int j=i+1; (j <=i+k) && (j < nums.size()); j++){
07                // cout << "i: " << i << "j: " << j << endl;
08                if(nums[i] == nums[j]) return true;
09            }
10        }
11        // cout << endl;
12        return false;
13    }
14};
15
16//Runtime: 1648 ms, faster than 5.45% of C++ online submissions for Contains Duplicate II.
17//Memory Usage: 10.1 MB, less than 100.00% of C++ online submissions for Contains Duplicate II.
18class Solution {
19public:
20    bool containsNearbyDuplicate(vector<int>& nums, int k) {
21        for(int i = 0; i+1 < nums.size(); i++){
22            // cout << "[" << i+1 << ", " << i+k << "]" << endl;
23            int finish = min((int)nums.size(), i+k+1);
24            if(find(nums.begin()+i+1, nums.begin()+finish, nums[i])
25              != nums.begin()+finish){
26                // cout << endl;
27                return true;
28            }
29        }
30        // cout << endl;
31        return false;
32    }
33};
34
35//https://leetcode.com/problems/contains-duplicate-ii/discuss/61372/Simple-Java-solution
36//Sliding window
37//Runtime: 40 ms, faster than 34.36% of C++ online submissions for Contains Duplicate II.
38//Memory Usage: 14.8 MB, less than 82.35% of C++ online submissions for Contains Duplicate II.
39class Solution {
40public:
41    bool containsNearbyDuplicate(vector<int>& nums, int k) {
42        set<int> myset;
43        for(int i = 0; i < nums.size(); i++){
44            //window : [i-k, i]
45            //so (i-k-1)th goes out of the window, need to remove it
46            if(i-k-1 >= 0) myset.erase(nums[i-k-1]);
47            /*
48            The single element versions (1) return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.
49            */
50            if(!myset.insert(nums[i]).second) return true;
51        }
52        return false;
53    }
54};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.