Contains Duplicate II - Array - Easy - LeetCode
💻 coding

Contains Duplicate II - Array - Easy - LeetCode

1 min read 114 words
1 min read
ShareWhatsAppPost on X
  • 1The problem requires finding two distinct indices in an array where the same value occurs within a specified distance k.
  • 2The provided solution uses a dictionary to track the indices of elements for efficient lookup and comparison.
  • 3The algorithm operates with a time complexity of O(n) and a space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem requires finding two distinct indices in an array where the same value occurs within a specified distance k."

Contains Duplicate II - Array - Easy - LeetCode

Given an array of integers and an integer k, find out whether 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 at most 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

public class Solution {
 public bool ContainsNearbyDuplicate(int[] nums, int k) {
 var map = new Dictionary<int,int>();
 for(int i=0;i<nums.Length;i++){
 if(map.ContainsKey(nums[i])){
 if(i-map[nums[i]]<=k){
 return true;
 }
 else{
 map[nums[i]]=i;
 }
 }
 else{
 map.Add(nums[i],i);
 }
 }
 
 return false;
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 25 September 2020 · 1 min read · 114 words

Part of AskGif Blog · coding

You might also like

Contains Duplicate II - Array - Easy - LeetCode | AskGif Blog