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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code