Contains Duplicate II LeetCode Solution

Here, We see Contains Duplicate II problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

Contains Duplicate II LeetCode Solution

Contains Duplicate II LeetCode Solution

Problem Statement ->

Given an integer array nums and an integer k, return true if there are two distinct indices 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

Contains Duplicate II Leetcode Solution C++ ->

class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_set<int> s; if (k <= 0) return false; if (k >= nums.size()) k = nums.size() - 1; for (int i = 0; i < nums.size(); i++) { if (i > k) s.erase(nums[i - k - 1]); if (s.find(nums[i]) != s.end()) return true; s.insert(nums[i]); } return false; } };
Code language: C++ (cpp)

Contains Duplicate II Leetcode Solution Java ->

class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { Set<Integer> set = new HashSet<Integer>(); for(int i = 0; i < nums.length; i++){ if(i > k) set.remove(nums[i-k-1]); if(!set.add(nums[i])) return true; } return false; } }
Code language: Java (java)

Contains Duplicate II Leetcode Solution JavaScript ->

var containsNearbyDuplicate = function(nums, k) { const hasmap = new Map(); for (let idx = 0; idx < nums.length; idx++) { if (idx - hasmap.get(nums[idx]) <= k) { return true; } hasmap.set(nums[idx], idx); } return false; };
Code language: JavaScript (javascript)

Contains Duplicate II Leetcode Solution Python ->

class Solution: def containsNearbyDuplicate(self, nums, k): dic = {} for i, v in enumerate(nums): if v in dic and i - dic[v] <= k: return True dic[v] = i return False
Code language: Python (python)