Contains Duplicate II
In this problem, we want to find if there are two distinct indices i
and j
in the array such that nums[i] == nums[j]
and the absolute difference between i
and j
is less than or equal to k
.
We can solve this problem by using a hash table to store the last index where each number was seen. We’ll iterate through the array and for each number, check if we’ve seen it before and if the difference between the current index and the last index where it was seen is less than or equal to k
. If both conditions are true, we’ll return true
. If not, we’ll update the hash table with the current index and continue.
Here’s the implementation:


This solution iterates through the array once, making the time complexity O(n), where n is the length of the array. The space complexity is also O(n), as in the worst case, we might store all the elements in the hash table.
10 Prerequisite LeetCode Problems
“Contains Duplicate II” focuses on the usage of Hashmaps/Hashsets, and maintaining a sliding window concept. Here are 10 simpler problems to practice as a foundation:
217. Contains Duplicate: This is a simpler version of Contains Duplicate II, and it will help you to understand how to detect duplicates using a HashSet.
349. Intersection of Two Arrays: This problem helps to understand how to use HashSets to find common elements in two arrays.
202. Happy Number: This problem uses a HashSet to remember previously seen numbers in a sequence.
141. Linked List Cycle: Even though this problem deals with linked lists, the principle of using a HashSet to detect duplicates is the same.
219. Contains Duplicate III: This problem is a bit more complex than Contains Duplicate II, but if you can understand and solve this one, Contains Duplicate II will be easier.
1. Two Sum: This problem involves using a HashMap to track previous elements in an array and their indices, similar to Contains Duplicate II.
705. Design HashSet: This problem helps you understand the underlying functionality of a HashSet, which is a crucial part of solving Contains Duplicate II.
594. Longest Harmonious Subsequence: This problem also uses a HashMap and has a similar flavor to the Contains Duplicate problems.
760. Find Anagram Mappings: It helps you understand how to use Hashmaps to track indices of elements, a useful tool in Contains Duplicate II.
532. Kdiff Pairs in an Array: This problem shares a similar concept where you need to find pairs within a certain difference.
These cover how to use HashSets and HashMaps, which are the main data structures needed for Contains Duplicate II.


Problem Classification
Array/Sequence Processing: The problem statement revolves around handling a list (or array) of integers, which implies the need for techniques related to array manipulation and traversal.
Searching: It requires determining if there are duplicate elements present in the list within a certain distance (or range) from each other, implying the necessity of search operations.
HashMap/Dictionary Usage: The usage of data structures like HashMap or dictionary is suggested by the need to track the index of elements in the list, and then use these indices for comparison. This implies the concept of keyvalue pairing, as used in HashMaps or dictionaries.
Distance Measurement: The need to check whether duplicates are within a certain distance or range from each other indicates the application of mathematical operations and comparisons.
These classifications are based on the concepts and strategies used to solve the problem, and not on any specific implementation or languagespecific details.
Clarification Questions
What are the clarification questions we can ask about this problem?
Identifying Problem Isomorphism
“Contains Duplicate II” can be mapped to “Minimum Size Subarray Sum”.
Both problems deal with contiguous subarrays and certain conditions they need to fulfill. In “Contains Duplicate II”, we need to find if there exist two indices i and j such that the absolute difference of i and j is at most k and the values at these indices are the same. In “Minimum Size Subarray Sum”, we need to find the minimal length of a contiguous subarray of which the sum is greater than or equal to a target integer.
In both cases, you might use a sliding window approach. In “Contains Duplicate II”, the window can shrink when a value is repeated within the defined range. In “Minimum Size Subarray Sum”, the window shrinks when the sum is larger than or equal to the target.
“Contains Duplicate II” is simpler because it only involves checking for duplicate elements within a certain range, whereas “Minimum Size Subarray Sum” involves checking for subarrays that meet a particular sum condition.
Language Agnostic Coding Drills
Understanding Lists/Arrays: Understanding how to iterate through the elements of a list or array and how to access individual elements based on their index.
Dictionary Operations: Understanding how to create a dictionary, add keyvalue pairs to it, and check for the existence of a key. Also, understanding how to update the value associated with a key.
IfElse Statements: Understanding how to use ifelse conditions to perform different operations based on the condition’s outcome.
Loops: Understanding how to use loops for repeated operations. Here, we’re using a for loop to iterate over the array.
Understanding of Abs Function: Understanding the builtin abs function, which returns the absolute value of the number.
Logical Operations: Understanding how to use logical operators, particularly the
and
operator and the<=
operator.
Step by step approach to solve the problem:
Start with an empty dictionary
hset
.Iterate over the input array
nums
with a for loop, with the index variable beingidx
.In each iteration, first check if the current number
nums[idx]
already exists in the dictionaryhset
and if the absolute difference between the current indexidx
and the stored index inhset
is less than or equal tok
.If the above condition is true, return
True
.If the current number does not exist in the dictionary or the condition in step 3 is not met, add the current number as a key to the dictionary
hset
, with its value being the current indexidx
.If the loop finishes without returning
True
, it means no such pair of duplicates was found, so returnFalse
.
This problemsolving approach requires knowledge of lists/arrays, dictionaries, loops, ifelse statements, and basic mathematical functions and operators. It provides a good exercise for practicing these concepts and building a fundamental understanding of how they can be combined to solve more complex problems.
Targeted Drills in Python
Understanding Lists/Arrays
Create a list of integers and print each item with its index.
1 2 3
numbers = [1, 2, 3, 4, 5] for idx, num in enumerate(numbers): print(f"Index: {idx}, Value: {num}")
Dictionary Operations
Create a dictionary from a list of integers where the integer is the key and its square is the value.
1 2 3
numbers = [1, 2, 3, 4, 5] squares = {num: num ** 2 for num in numbers} print(squares)
IfElse Statements
Check if a number exists in the dictionary, if it does print its value else print a message.
1 2 3 4 5 6
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} num = 3 if num in squares: print(squares[num]) else: print(f"{num} not in dictionary")
Loops
Print the first 5 even numbers.
1 2
for i in range(2, 11, 2): print(i)
Understanding of Abs Function
Print the absolute difference between two numbers.
1 2 3
num1 = 5 num2 = 10 print(abs(num1  num2))
Logical Operations
Check if a number is within a certain range.
1 2 3 4 5
num = 7 if num >= 5 and num <= 10: print("Number is within range") else: print("Number is out of range")
You can practice these drills individually to get a grasp on each concept. After you’re comfortable with each of them, you can combine these concepts to solve the original problem.