219. Contains Duplicate II
Approach 1: Brute Force
The easiest solution is to brute force our way through for each element in the array and try to find another one close enough to satisfy our condition.
As expected this solution exceeds the time limit at test case 22/23
Time Complexity: O(n²)
Space Complexity: O(1)
Approach 2: Sliding Window
We can take the sliding window approach by looking at the next 'k' positions in the array and looking for matches.
This solution although accepted doesn't really have the best runtime, coming in at a measly 66.5% percentile.
Time Complexity: O(nk) (Lookup in sets is O(1) in Python)
Space Complexity: O(k)
Approach 3: Dictionary of last seen positions
We can iterate over the array and keep track of where we see a number, and then if we see it again, check to see if it passes the distance constraint.
As expected, this solution passes with flying colours coming in at a solid 98.3% percentile among other solutions.
Time Complexity: O(n)
Space Complexity: O(n)
Last updated