Find All K-Distant Indices in an Array
You receive a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key.
Find and provide a list of all k-distant indices sorted in increasing order.
Input: nums = [3,4,9,1,3,9,5], key = 9, k = 1
Output: [1,2,3,4,5,6]
Explanation: Here, nums[2] == key and nums[5] == key.
-
For index 0,
|0 - 2| > kand|0 - 5| > k, so there is nojwhere|0 - j| <= kandnums[j] == key. Thus, 0 is not a k-distant index. -
For index 1,
|1 - 2| <= kandnums[2] == key, so 1 is a k-distant index. -
For index 2,
|2 - 2| <= kandnums[2] == key, so 2 is a k-distant index. -
For index 3,
|3 - 2| <= kandnums[2] == key, so 3 is a k-distant index. -
For index 4,
|4 - 5| <= kandnums[5] == key, so 4 is a k-distant index. -
For index 5,
|5 - 5| <= kandnums[5] == key, so 5 is a k-distant index. -
For index 6,
|6 - 5| <= kandnums[5] == key, so 6 is a k-distant index.
Thus, we provide [1,2,3,4,5,6] which is sorted in increasing order.
Input: nums = [2,2,2,2,2], key = 2, k = 2
Output: [0,1,2,3,4]
Explanation: For all indices i in nums, there exists some index j such that |i - j| <= k and nums[j] == key, so every index is a k-distant index.
Hence, we provide [0,1,2,3,4].
Constraints
1 <= nums.length <= 10001 <= nums[i] <= 1000keyis an integer from the arraynums.1 <= k <= nums.length
Did this problem appear in one of your interviews?
Responses stay private.
