I like to read this solution as a small machine: keep the useful information, throw away the noise. For 220. Contains Duplicate III, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. 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: straightforward implementation.
The notes already sitting in the source point us in the right direction:
- Brute force
- TLE
- 40 / 41 test cases passed.
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are containsNearbyAlmostDuplicate.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
- 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:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
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), space: O(N)
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Brute force
02//TLE
03//40 / 41 test cases passed.
04class Solution {
05public:
06 bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
07 int n = nums.size();
08
09 for(int i = 0; i < n; ++i){
10 for(int j = i+1; j <= min(n-1, i+k); ++j){
11 if(abs((long long)nums[i]-nums[j]) <= t){
12 return true;
13 }
14 }
15 }
16
17 return false;
18 }
19};
20
21//Bucket
22//https://leetcode.com/problems/contains-duplicate-iii/discuss/61645/AC-O(N)-solution-in-Java-using-buckets-with-explanation
23//Runtime: 28 ms, faster than 79.23% of C++ online submissions for Contains Duplicate III.
24//Memory Usage: 11.4 MB, less than 36.26% of C++ online submissions for Contains Duplicate III.
25//time: O(N), space: O(N)
26class Solution {
27public:
28 bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
29 //abs(i-j) = k < 1: not reasonable
30 //abs(nums[i]-nums[j]) = t < 0: not reasonable
31 if(k < 1 || t < 0) return false;
32
33 unordered_map<long long, long long> buckets;
34 int n = nums.size();
35
36 for(int i = 0; i < n; ++i){
37 //since nums[i] could be negative, so we add INT_MIN to make it starts from 0
38 long long remappedNum = (long long)nums[i] - INT_MIN;
39 long long bucket = remappedNum / ((long long)t+1);
40
41 //find a number in [num-t,num+t] in the range [i-k,i+k]
42 if(buckets.find(bucket) != buckets.end() || //duplicate key: valid j found!
43 buckets.find(bucket-1) != buckets.end() && //find in previous bucket
44 remappedNum - buckets[bucket-1] <= t ||
45 buckets.find(bucket+1) != buckets.end() && //find in next bucket
46 buckets[bucket+1] - remappedNum <= t
47 ){
48 return true;
49 }
50
51 if(buckets.size() >= k){
52 long long lastRemappedNum = (long long)nums[i-k] - INT_MIN;
53 long long lastBucket = lastRemappedNum / ((long long)t+1);
54 /*
55 buckets[lastBucket] must only contains nums[i-k],
56 if not, that means we already found a valid j,
57 at that situation, we are already returned
58 */
59 buckets.erase(lastBucket);
60 }
61
62 //currently buckets[bucket] is empty
63 buckets[bucket] = remappedNum;
64 }
65
66 return false;
67 }
68};
69
70//Tree set
71//https://leetcode.com/problems/contains-duplicate-iii/discuss/61655/Java-O(N-lg-K)-solution
72//time: O(NlogK), N: #insertion/deletion, K: size of the tree set
73//space: O(K)
74class Solution {
75public:
76 bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
77 set<long long> vals;
78 int n = nums.size();
79
80 for(int i = 0; i < n; ++i){
81 //smallest element >= nums[i]-t
82 set<long long>::iterator floor = vals.lower_bound((long long)nums[i]-t);
83 if(floor != vals.end() && *floor <= nums[i]) return true;
84
85 //smallest element > nums[i]+t
86 set<long long>::iterator ceil = vals.upper_bound((long long)nums[i]+t);
87 if(ceil != vals.begin()){
88 //largest element <= nums[i]+t
89 ceil = prev(ceil);
90 if(*ceil >= nums[i]) return true;
91 }
92
93 vals.insert(nums[i]);
94 if(i >= k) vals.erase(nums[i-k]);
95 }
96
97 return false;
98 }
99};
Cost