KatInterview

219. Contains Duplicate II

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to determine if there are two identical numbers in an integer array nums such that the absolute difference between their indices is at most k. Specifically, we need to find if there exist indices i and j where i != j, nums[i] == nums[j], and abs(i - j) <= k.

Solution

Contains Duplicate II in Python

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        # Use a dictionary (hash map) to store the most recent index of each number.
        # Key: number, Value: index
        num_indices = {}
        
        for i, num in enumerate(nums):
            # Check if the current number has been seen before.
            if num in num_indices:
                # If it has, check if the distance between indices is within k.
                prev_index = num_indices[num]
                if i - prev_index <= k:
                    return True
            
            # Update the dictionary with the current number's most recent index.
            # This is done for every element to keep track of its latest position.
            num_indices[num] = i
            
        # If the loop completes without finding a suitable pair, return false.
        return False

Contains Duplicate II in Java

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        // Use a HashMap to store the most recent index of each number.
        // Key: number, Value: index
        Map<Integer, Integer> numIndices = new HashMap<>();
        
        for (int i = 0; i < nums.length; i++) {
            int currentNum = nums[i];
            
            // Check if the current number has been seen before.
            if (numIndices.containsKey(currentNum)) {
                // If it has been seen, get the previous index.
                int prevIndex = numIndices.get(currentNum);
                
                // Check if the distance between indices is within k.
                if (i - prevIndex <= k) {
                    return true;
                }
            }
            
            // Update the map with the current number's most recent index.
            // This is done for every element to keep track of its latest position.
            numIndices.put(currentNum, i);
        }
        
        // If we iterate through the whole array without finding such a pair, return false.
        return false;
    }
}

Contains Duplicate II in C++

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        // Use an unordered_map to store the most recent index of each number.
        // Key: number, Value: index
        std::unordered_map<int, int> num_indices;
        
        for (int i = 0; i < nums.size(); ++i) {
            int current_num = nums[i];
            
            // Check if the current number has been seen before.
            if (num_indices.count(current_num)) {
                // If it has been seen, check if the distance between indices is within k.
                int prev_index = num_indices[current_num];
                if (i - prev_index <= k) {
                    return true;
                }
            }
            
            // Update the map with the current number's most recent index.
            // This is done regardless of whether the duplicate was found within k,
            // because we always need the most recent index for future checks.
            num_indices[current_num] = i;
        }
        
        // If the loop completes without finding a suitable pair, return false.
        return false;
    }
};

Contains Duplicate II in TypeScript

function containsNearbyDuplicate(nums: number[], k: number): boolean {
    // Use a Map to store the most recent index of each number.
    // Key: number, Value: index
    const numIndices = new Map<number, number>();
    
    for (let i = 0; i < nums.length; i++) {
        const currentNum = nums[i];
        
        // Check if the current number has been seen before.
        if (numIndices.has(currentNum)) {
            // If it has, get the previous index.
            // Using ! for non-null assertion as .has() guarantees existence.
            const prevIndex = numIndices.get(currentNum)!;
            
            // Check if the distance between indices is within k.
            if (i - prevIndex <= k) {
                return true;
            }
        }
        
        // Update the map with the current number's most recent index.
        // This is done for every element to keep track of its latest position.
        numIndices.set(currentNum, i);
    }
    
    // If we iterate through the whole array without finding such a pair, return false.
    return false;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.