219. Contains Duplicate II LeetCode Solution

In this guide, you will get 219. Contains Duplicate II LeetCode Solution with the best time and space complexity. The solution to Contains Duplicate II problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Contains Duplicate II solution in C++
  4. Contains Duplicate II solution in Java
  5. Contains Duplicate II solution in Python
  6. Additional Resources
219. Contains Duplicate IILeetCode Solution image

Problem Statement of Contains Duplicate II

Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i – j) <= k.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

Constraints:

1 <= nums.length <= 105
-109 <= nums[i] <= 109
0 <= k <= 105

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

219. Contains Duplicate II LeetCode Solution in C++

class Solution {
 public:
  bool containsNearbyDuplicate(vector<int>& nums, int k) {
    unordered_set<int> seen;

    for (int i = 0; i < nums.size(); ++i) {
      if (!seen.insert(nums[i]).second)
        return true;
      if (i >= k)
        seen.erase(nums[i - k]);
    }

    return false;
  }
};
/* code provided by PROGIEZ */

219. Contains Duplicate II LeetCode Solution in Java

class Solution {
  public boolean containsNearbyDuplicate(int[] nums, int k) {
    Set<Integer> seen = new HashSet<>();

    for (int i = 0; i < nums.length; ++i) {
      if (!seen.add(nums[i]))
        return true;
      if (i >= k)
        seen.remove(nums[i - k]);
    }

    return false;
  }
}
// code provided by PROGIEZ

219. Contains Duplicate II LeetCode Solution in Python

class Solution:
  def containsNearbyDuplicate(self, nums: list[int], k: int) -> bool:
    seen = set()

    for i, num in enumerate(nums):
      if i > k:
        seen.remove(nums[i - k - 1])
      if num in seen:
        return True
      seen.add(num)

    return False
 # code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.