Sponsored
Sponsored
This approach utilizes a hash map (dictionary) to maintain a mapping between array elements and their indices. As we iterate through the array, we check if the current element already exists in the hash map. If it does, we calculate the difference between the current index and the stored index and check if it is less than or equal to k
. If this condition is met, we return true
. Otherwise, we update the hash map with the current index for the element.
Time Complexity: O(n), where n is the number of elements in the array, since each insert/find operation is linear.
Space Complexity: O(min(n, k)), where n is the number of elements in the array, because we store at most k elements in the map at any time.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public bool ContainsNearbyDuplicate(int[] nums, int k) {
6 Dictionary<int, int> map = new Dictionary<int, int>();
7 for (int i = 0; i < nums.Length; i++) {
8 if (map.ContainsKey(nums[i]) && i - map[nums[i]] <= k) {
9 return true;
10 }
11 map[nums[i]] = i;
12 }
13 return false;
14 }
15}
Within the C# environment, a Dictionary
is used to map array values to indices. During the traversal of the array, if an entry is located within the distance constraint, the procedure returns true
; otherwise, it adjusts the index value within the dictionary.
This method employs a sliding window (of length k
) to automatically invalidate indices of prior numbers as the window advances through the array. The structure operates similarly to a hash set within the k
-restricted scope, resulting in more direct checks and validations during index alterations.
Time Complexity: O(n*k), as each number is recalculated through prior windows.
Space Complexity: O(k), correlating with the contiguous window used.
1
The JavaScript template holds Set
operations crucial for sliding window execution. Its membership verification facilitates collective removal and insertion based on the condition, meaning the index advances steadily while regulating observations.