Find All K-Distant Indices in an Array
|
|
Here’s a step-by-step explanation of the solution:
Create a List of Indices: Identify the indices in
nums
where the value is equal tokey
.Initialize Result List: Initialize an empty list
result
to keep track of the k-distant indices.Iterate through
nums
: For each indexi
ofnums
, check if it is a k-distant index by comparing with the identified indices ofkey
.- Check k-Distance: If there exists an index
j
in the list of key indices such that the difference|i - j|
is less than or equal tok
, then add indexi
to the result.
- Check k-Distance: If there exists an index
Return the Result: Finally, return the
result
list which consists of all the k-distant indices sorted in increasing order.
The code first finds the indices of key
in nums
and then iterates through each index of nums
to check if it is a k-distant index by comparing with the key indices. If found, the index is added to the result. Finally, the result is returned.