Find All K-Distant Indices in an Array - Problem

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 at least one index j such that |i - j| <= k and nums[j] == key.

Return a list of all k-distant indices sorted in increasing order.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,4,9,1,4,9], key = 4, k = 1
Output: [0,1,2,3,4,5]
💡 Note: Key 4 appears at indices 1 and 4. For k=1: index 1 covers [0,1,2], index 4 covers [3,4,5]. Together they cover all indices.
Example 2 — Sparse Keys
$ Input: nums = [2,2,2,2,2], key = 2, k = 2
Output: [0,1,2,3,4]
💡 Note: Key 2 appears at every index. With k=2, every position is within distance 2 of multiple key occurrences.
Example 3 — No Key Found
$ Input: nums = [1,2,3], key = 4, k = 1
Output: []
💡 Note: Key 4 does not appear in the array, so no indices are k-distant.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 1000
  • 1 ≤ key ≤ 1000
  • 0 ≤ k ≤ nums.length

Visualization

Tap to expand
Find All K-Distant Indices in an Array INPUT nums array: 3 i=0 4 i=1 9 i=2 1 i=3 4 i=4 9 i=5 Red = key positions (4) nums = [3,4,9,1,4,9] key = 4 k = 1 |i - j| <= k where nums[j]=key Distance k=1 from key indices: j=1: covers i=0,1,2 j=4: covers i=3,4,5 ALGORITHM STEPS (Two-Pass Optimization) 1 Find Key Positions Locate all j where nums[j]=key keyPos = [1, 4] 2 Pass 1: Expand Left For each keyPos, mark [j-k, j] j=1: mark 0,1 | j=4: mark 3,4 3 Pass 2: Expand Right For each keyPos, mark [j, j+k] j=1: mark 1,2 | j=4: mark 4,5 4 Collect Results Return all marked indices Union: [0,1,2,3,4,5] Coverage Table Index 0 1 2 3 4 5 Covered OK OK OK OK OK OK FINAL RESULT All K-Distant Indices: 0 1 2 3 4 5 Output: [0, 1, 2, 3, 4, 5] Why All Indices? From key at j=1: |0-1|=1 <= k=1 --> i=0 OK |1-1|=0 <= k=1 --> i=1 OK |2-1|=1 <= k=1 --> i=2 OK From key at j=4: |3-4|=1 <= k=1 --> i=3 OK |4-4|=0 <= k=1 --> i=4 OK |5-4|=1 <= k=1 --> i=5 OK Key Insight: Two-pass optimization avoids checking every (i,j) pair. First pass: find all key positions. Second pass: expand k distance from each key position. Time: O(n), Space: O(n). The ranges overlap, ensuring complete coverage: [0,2] from j=1 and [3,5] from j=4. TutorialsPoint - Find All K-Distant Indices in an Array | Two-Pass Optimization
Asked in
Microsoft 15 Google 12
18.5K Views
Medium Frequency
~12 min Avg. Time
432 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen