Some Space Optimisations
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 MY FIRST APPROACH: A very valid solution class Solution : def containsNearbyDuplicate ( self , nums : list [ int ], k : int ) -> bool : ref = {} for i in range ( len ( nums )): if nums [ i ] not in ref : ref [ nums [ i ]] = i else : if…
Given an integer array nums and an integer k, the task is to determine if there exist two distinct indices i and j in the array such that the values at those indices are equal (nums[i] == nums[j]), and the absolute difference between the indices is equal to k (abs(i - j) = k). The provided solution demonstrates two different approaches to solve this problem.
The first approach creates a dictionary named ref to store the values from the nums array as keys and their corresponding indices as values. The code iterates through the nums array using a for loop, starting from index 0 to the length of nums. For each index i, the code checks if the value at that index is not already present in the ref dictionary. If the value is not present, it adds the value as a key and the index i as its corresponding value in the ref dictionary.
If the value at index i is already present in the ref dictionary, the code checks if the absolute difference between the current index i and the stored index of that value in the ref dictionary equals k. If the condition is satisfied, the function returns True, indicating the presence of two distinct indices i and j that meet the specified criteria. If the condition is not met, the code updates the value in the ref dictionary with the latest index i.
The second approach optimizes the space complexity by using a set named ref instead of a dictionary. The code also iterates through the nums array using a for loop, starting from index 0 to the length of nums. For each index i, the code checks if the length of the ref set exceeds k. If the length exceeds k, the code removes the element at the index (k - i) from the ref set. This ensures that the ref set only stores a maximum of k elements at any given time.
If the value at index i is already present in the ref set, the function returns True, indicating the presence of two distinct indices i and j that meet the specified criteria. If the value is not present in the ref set, the code adds the value to the ref set. Finally, if no such pair of indices is found, the function returns False.
Both approaches aim to solve the problem of finding two distinct indices i and j in the nums array where nums[i] == nums[j] and abs(i - j) = k. The second approach optimizes the space complexity by using a set instead of a dictionary and ensures that the set size remains limited to k elements at any given time.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.