Find All K-Distant Indices in an Array - Problem
You're given a 0-indexed integer array nums and two integers key and k. Your task is to find all indices that are "close enough" to any occurrence of the key value.
An index i is considered k-distant if there exists at least one index j where:
nums[j] == key(j points to our target value)|i - j| <= k(i is within k positions of j)
Goal: Return a list of all k-distant indices sorted in increasing order.
Example: If nums = [3,4,9,1,3,9,5], key = 9, and k = 1, then indices 2 and 5 contain the value 9. The k-distant indices are [1,2,3,4,5,6] because they're all within distance 1 of either index 2 or 5.
Input & Output
example_1.py โ Basic case
$
Input:
nums = [3,4,9,1,3,9,5], key = 9, k = 1
โบ
Output:
[1,2,3,4,5,6]
๐ก Note:
The key 9 appears at indices 2 and 5. Index 1 is k-distant because |1-2| = 1 โค k. Index 2 is k-distant because it contains the key. Index 3 is k-distant because |3-2| = 1 โค k. Index 4 is k-distant because |4-5| = 1 โค k. Index 5 is k-distant because it contains the key. Index 6 is k-distant because |6-5| = 1 โค k. Index 0 is not k-distant because |0-2| = 2 > k and |0-5| = 5 > k.
example_2.py โ No overlapping coverage
$
Input:
nums = [2,2,2,2], key = 2, k = 2
โบ
Output:
[0,1,2,3]
๐ก Note:
Every element is the key value 2, so all indices are k-distant by definition. Since each index contains the key, the distance from any index to itself is 0, which is โค k = 2.
example_3.py โ Large distance
$
Input:
nums = [1,1000,1,1000], key = 1000, k = 0
โบ
Output:
[1,3]
๐ก Note:
The key 1000 appears at indices 1 and 3. With k = 0, only indices that exactly contain the key are k-distant. Therefore, only indices 1 and 3 qualify as k-distant indices.
Constraints
- 1 โค nums.length โค 1000
- 1 โค nums[i] โค 1000
- key is an integer from the range [1, 1000]
- 0 โค k โค nums.length
Visualization
Tap to expand
Understanding the Visualization
1
Identify Radio Towers
Find all positions where towers (key values) are located
2
Calculate Coverage Zones
Each tower broadcasts k miles in both directions
3
Mark Signal Reception
Any mile marker within range receives the signal
4
Collect All Covered Areas
Gather all positions that receive at least one signal
Key Takeaway
๐ฏ Key Insight: Instead of checking each position's distance to every tower, find towers and immediately expand their coverage zones - this eliminates redundant distance calculations and achieves optimal performance.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code