#2200
Find All K-Distant Indices in an Array
EasyArrayTwo PointersHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a single pass to identify all indices of the key and then calculates the k-distant indices based on those positions. This is efficient because we avoid redundant checks.
⚙️
Algorithm
3 steps- 1Step 1: Create a list to store indices of the key in the array.
- 2Step 2: For each index of the key found, calculate the range of k-distant indices and add them to a set to avoid duplicates.
- 3Step 3: Convert the set to a sorted list and return it.
solution.py7 lines
1def findKDistantIndices(nums, key, k):
2 key_indices = [i for i, num in enumerate(nums) if num == key]
3 k_distant_indices = set()
4 for index in key_indices:
5 for i in range(max(0, index - k), min(len(nums), index + k + 1)):
6 k_distant_indices.add(i)
7 return sorted(k_distant_indices)ℹ
Complexity note: The time complexity is O(n) because we make a single pass to find key indices and then another pass to add k-distant indices. The space complexity is O(n) due to the storage of indices in a set.
- 1Using a set helps avoid duplicate indices efficiently.
- 2Understanding the range of indices to check is crucial for optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.