Find All K-Distant Indices in an Array (LeetCode 2200): Solution and Explanation
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
- Set
res = []andstart = 0. - Scan
jfrom 0 to n - 1. Skip values that are notkey. - For a key at
j, setlo = max(start, j - k)andhi = min(n - 1, j + k). - Append
lo, lo + 1, ..., hitores(nothing iflo > hi), then setstart = hi + 1. - 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
- j = 0 and j = 1 hold 3 and 4, not 9, so nothing happens.
- j = 2 holds 9. Its window is [1, 3], start is 0, so add 1, 2, 3 and set start = 4.
- j = 3 and j = 4 are not 9.
- j = 5 holds 9. Its window is [4, 6]; start is 4, so add 4, 5, 6 and set start = 7.
- 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 res1class Solution {
2 public List<Integer> findKDistantIndices(int[] nums, int key, int k) {
3 List<Integer> res = new ArrayList<>();
4 int start = 0, n = nums.length;
5 for (int j = 0; j < n; j++) {
6 if (nums[j] == key) {
7 int lo = Math.max(start, j - k);
8 int hi = Math.min(n - 1, j + k);
9 for (int i = lo; i <= hi; i++) {
10 res.add(i);
11 }
12 start = hi + 1;
13 }
14 }
15 return res;
16 }
17}1class Solution {
2public:
3 vector<int> findKDistantIndices(vector<int>& nums, int key, int k) {
4 vector<int> res;
5 int start = 0, n = nums.size();
6 for (int j = 0; j < n; j++) {
7 if (nums[j] == key) {
8 int lo = max(start, j - k);
9 int hi = min(n - 1, j + k);
10 for (int i = lo; i <= hi; i++) {
11 res.push_back(i);
12 }
13 start = hi + 1;
14 }
15 }
16 return res;
17 }
18};Time and space complexity
O(n)
The scan visits each index once, and start only moves forward, so each index is appended at most once.
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.