The problem is as follows:
You are given a 0-indexed integer array nums and two integers key and k. A k-distant index in nums is an index i such that there exists at least one index j in nums where nums[j] == key and the absolute difference between i and j is less than or equal to k.
Return a list of all k-distant indices sorted in increasing order.
nums constrained to a specific range?key be any integer value, and will k always be non-negative?nums = [3, 4, 9, 1, 3, 9, 5], key = 9, k = 2 should return [1, 2, 3, 4, 5, 6].nums has at least one occurrence of key?j where nums[j] == key.j, mark all indices i in the range [j - k, j + k] as valid k-distant indices.def findKDistantIndices(nums, key, k):
key_indices = []
n = len(nums)
# Finding all the indices where nums[j] == key
for idx in range(n):
if nums[idx] == key:
key_indices.append(idx)
k_distant_indices = set()
# For each key index j, mark the indices i in the range [j - k, j + k]
for j in key_indices:
start = max(0, j - k)
end = min(n - 1, j + k)
for i in range(start, end + 1):
k_distant_indices.add(i)
# Return the sorted list of k-distant indices
return sorted(k_distant_indices)
# Example Usage
nums = [3, 4, 9, 1, 3, 9, 5]
key = 9
k = 2
print(findKDistantIndices(nums, key, k))
# Output: [1, 2, 3, 4, 5, 6]
nums array.key occurrences (let’s call it m), and for each key occurrence we need to mark up to 2k + 1 indices.Therefore, in the worst case, the time complexity is O(n + m * k + n log n). Given typical constraints, this solution should be efficient enough for large inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?