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 K-Distant Indices: Coverage Zone Conceptnums = [3,4,9,1,4,9], key = 4, k = 1349149012345Zone 1: k=1Zone 2: k=1Coverage zones overlap to include all indicesResult: [0,1,2,3,4,5]
Understanding the Visualization
1
Input
Array with key occurrences and distance parameter k
2
Coverage
Each key creates coverage zone of radius k
3
Output
All indices within any coverage zone
Key Takeaway
🎯 Key Insight: Each key occurrence creates a coverage zone, and we need all indices within any zone
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