Find All K-Distant Indices in an Array (LeetCode 2200): Solution and Explanation

Easy
Two Pointers
Array

Given an array nums, a value key and a distance k, return every index i that is at most k positions away from some index holding key, in increasing order.

Intuition

Flip the definition around: instead of asking each index whether a key is nearby, let each key mark everything near it. A key at index j marks the window [j - k, j + k].

The answer is the union of these windows. Because keys are found from left to right, each new window starts no earlier and ends no earlier than the one before it.

That makes the union easy to emit in order. Remember start, the first index not yet added, and only add the part of each new window at or after start.

Approach: Windows merged with a start pointer

  1. Set res = [] and start = 0.
  2. Scan j from 0 to n - 1. Skip values that are not key.
  3. For a key at j, set lo = max(start, j - k) and hi = min(n - 1, j + k).
  4. Append lo, lo + 1, ..., hi to res (nothing if lo > hi), then set start = hi + 1.
  5. Return res; it is already sorted and has no duplicates.

Step-by-step example

nums = [3,4,9,1,3,9,5], key = 9, k = 1
  1. j = 0 and j = 1 hold 3 and 4, not 9, so nothing happens.
  2. j = 2 holds 9. Its window is [1, 3], start is 0, so add 1, 2, 3 and set start = 4.
  3. j = 3 and j = 4 are not 9.
  4. j = 5 holds 9. Its window is [4, 6]; start is 4, so add 4, 5, 6 and set start = 7.
  5. j = 6 is not 9. The answer is [1,2,3,4,5,6].

Code: Python, Java, C++

1class Solution:
2    def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:
3        res = []
4        start = 0
5        for j, x in enumerate(nums):
6            if x == key:
7                lo = max(start, j - k)
8                hi = min(len(nums) - 1, j + k)
9                res.extend(range(lo, hi + 1))
10                start = hi + 1
11        return res
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

The scan visits each index once, and start only moves forward, so each index is appended at most once.

Space

O(1)

Apart from the output list, only j, start, lo and hi are stored.

Other approaches

Brute force over all pairs (time O(n^2), space O(1))

For every i, look at every j and check whether |i - j| <= k and nums[j] == key. Simple and fine for n = 1000, but it does n^2 comparisons.

Difference array (time O(n), space O(n))

Add +1 at j - k and -1 at j + k + 1 for each key, take prefix sums, and output indices with a positive count. Also linear, but it needs an extra array.

Common mistakes

  • Adding each whole window without the start pointer. Overlapping windows then add the same index twice, and a set plus a sort is needed to clean up.
  • Forgetting to clip the window to [0, n - 1]. Keys near either end produce windows that run off the array.
  • Stopping after the first key. Every occurrence of key opens its own window, so the scan has to run to the end of the array.
  • Treating k as exclusive. The condition is |i - j| <= k, so the window includes both j - k and j + k.

Frequently asked questions

Why is the output sorted without calling sort?

Windows are added in the order their keys appear, each new window ends at or after the previous one, and only indices at or after start are added. So every appended index is larger than the ones before it.

Can a window add nothing?

Yes. With two keys next to each other and a large k, the first window can already reach as far as the second one, so lo ends up greater than hi and nothing new is added.

Where are the two pointers?

j scans for keys and start trails behind as the frontier of indices already emitted. start never moves backward, which is what keeps the work linear.