Difficulty: Easy | Acceptance: 77.30% | Paid: No Topics: Array, Two Pointers
You are given 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 an index j such that nums[j] == key and abs(i - j) <= k.
Return the list of all k-distant indices sorted in increasing order.
- Examples
- Constraints
- Brute Force
- Boolean Array Marking
- Precompute Nearest Key
Examples
Input: nums = [3,4,9,1,3,9,2], key = 9, k = 1
Output: [1,2,3,4,5,6]
Explanation: The k-distant indices with key = 9 are:
- nums[2] == 9 and abs(0 - 2) > 1
- nums[2] == 9 and abs(1 - 2) <= 1
- nums[2] == 9 and abs(2 - 2) <= 1
- nums[5] == 9 and abs(3 - 5) > 1
- nums[5] == 9 and abs(4 - 5) <= 1
- nums[5] == 9 and abs(5 - 5) <= 1
- nums[5] == 9 and abs(6 - 5) <= 1
Hence, the k-distant indices are [1,2,3,4,5,6].
Input: nums = [2,2,2,2,2], key = 2, k = 2
Output: [0,1,2,3,4]
Explanation: All indices are k-distant indices because every element is equal to key and the distance is at most 2.
Constraints
1 <= nums.length <= 1000
1 <= nums[i] <= 1000
key is an element in nums.
1 <= k <= nums.length
Brute Force
Intuition
Check every index i against every index j to see if the condition nums[j] == key and abs(i - j) <= k holds true.
Steps
- Initialize an empty list
result. - Iterate through each index
ifrom 0 ton-1. - For each
i, iterate through each indexjfrom 0 ton-1. - If
nums[j] == keyandabs(i - j) <= k, additoresultand break the inner loop (since we only need one validjperi). - Return
result.
class Solution:
def findKDistantIndices(self, nums: list[int], key: int, k: int) -> list[int]:
n = len(nums)
res = []
for i in range(n):
for j in range(n):
if nums[j] == key and abs(i - j) <= k:
res.append(i)
break
return resComplexity
- Time: O(n²)
- Space: O(1) (excluding output)
- Notes: Simple to implement but inefficient for large arrays.
Boolean Array Marking
Intuition
Instead of checking every i, find the valid ranges for i based on where key is located. For every index j where nums[j] == key, all indices i in the range [j-k, j+k] are valid.
Steps
- Create a boolean array
visitedof sizen, initialized to false. - Iterate through the array to find indices
jwherenums[j] == key. - For each such
j, mark all indicesifrommax(0, j-k)tomin(n-1, j+k)as true in thevisitedarray. - Collect all indices
iwherevisited[i]is true. - Return the collected indices.
class Solution:
def findKDistantIndices(self, nums: list[int], key: int, k: int) -> list[int]:
n = len(nums)
visited = [False] * n
for j in range(n):
if nums[j] == key:
start = max(0, j - k)
end = min(n - 1, j + k)
for i in range(start, end + 1):
visited[i] = True
return [i for i in range(n) if visited[i]]Complexity
- Time: O(n * k)
- Space: O(n)
- Notes: More efficient than brute force when k is small.
Precompute Nearest Key
Intuition
For each index i, we only need to know the closest key to the left and right. We can precompute these distances in two passes.
Steps
- Create arrays
leftandrightof sizen. - Iterate left to right to fill
leftwith the index of the nearestkeyseen so far. - Iterate right to left to fill
rightwith the index of the nearestkeyseen so far. - Iterate
ifrom 0 ton-1. Check ifabs(i - left[i]) <= korabs(i - right[i]) <= k. - If yes, add
ito result.
class Solution:
def findKDistantIndices(self, nums: list[int], key: int, k: int) -> list[int]:
n = len(nums)
left = [-1] * n
right = [-1] * n
last = -1
for i in range(n):
if nums[i] == key:
last = i
left[i] = last
last = -1
for i in range(n - 1, -1, -1):
if nums[i] == key:
last = i
right[i] = last
res = []
for i in range(n):
if (left[i] != -1 and abs(i - left[i]) <= k) or (right[i] != -1 and abs(i - right[i]) <= k):
res.append(i)
return resComplexity
- Time: O(n)
- Space: O(n)
- Notes: Most efficient time complexity, but uses extra space for the
leftandrightarrays.