Find All K-Distant Indices in an Array

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
    def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:
        # Step 1: Create a list of indices where the value is equal to key
        key_indices = []
        for i in range(len(nums)):
            if nums[i] == key:
                key_indices.append(i)

        # Step 2: Initialize result list
        result = []

        # Step 3: Iterate through nums and check if each index is a k-distant index
        for i in range(len(nums)):
            is_k_distant = False

            # Check k-distance with each index of key
            for j in key_indices:
                if abs(i - j) <= k:
                    is_k_distant = True
                    break

            if is_k_distant:
                result.append(i)

        # Step 4: Return the result
        return result

Here’s a step-by-step explanation of the solution:

  1. Create a List of Indices: Identify the indices in nums where the value is equal to key.

  2. Initialize Result List: Initialize an empty list result to keep track of the k-distant indices.

  3. Iterate through nums: For each index i of nums, check if it is a k-distant index by comparing with the identified indices of key.

    • 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 to k, then add index i to the result.
  4. 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.