LeetCode 219: Contains Duplicate II Solution

Master LeetCode problem 219 (Contains Duplicate II), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

219. Contains Duplicate II

Problem Explanation

Explanation

To solve this problem, we can iterate through the array and keep track of the indices of each number we encounter using a HashMap. For each number, if it already exists in the HashMap, we check if the absolute difference of the current index and the previous index of that number is less than or equal to k. If it is, we return true. If we finish iterating through the array without finding any such pair, we return false.

  • Time complexity: O(n) where n is the number of elements in the array.
  • Space complexity: O(min(n, k)) where n is the number of elements in the array and k is the value of k.

Solution Code

import java.util.HashMap;

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) {
                return true;
            }
            map.put(nums[i], i);
        }
        
        return false;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 219 (Contains Duplicate II)?

This page provides optimized solutions for LeetCode problem 219 (Contains Duplicate II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 219 (Contains Duplicate II)?

The time complexity for LeetCode 219 (Contains Duplicate II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 219 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 219 in Java, C++, or Python.

Back to LeetCode Solutions