š¹ Problem: 2200. Find All K-Distant Indices in an Array
Difficulty: Easy
Tags: #TwoPointers, #Simulation
š Problem Summary
You're given an array
nums, an integerkey, and another integerk.
Find all indicesisuch that there exists at least one indexjwhere:
nums[j] == keyandabs(i - j) <= kReturn the list of such indices in increasing order.
š§ My Thought Process
-
Brute Force Idea:
- For every index
i, check every indexjand see ifnums[j] == keyandabs(i-j) <= k. - Time Complexity: O(n²) ā too slow for larger inputs. But you can submit this in leetcode.
- For every index
-
Optimized Strategy:
- Iterate through the array and whenever we find
nums[i] == key, we know that: - All indices from
i-ktoi+kare validk-distant indices. - We use
max(right, i-k)as the start so that we don't add overlapping ranges twice. - Update
right = min(n, i+k+1)to track the farthest index added so far. - We directly
extendtheanslist with that range.
- Iterate through the array and whenever we find
Algorithm Used:
[[two_pointer]]
āļø Code Implementation (Python)
class Solution:
def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:
ans = []
n = len(nums)
right = 0
for i in range(n):
if nums[i] == key:
left = max(right, i-k)
right = min(n, i+k+1)
ans.extend(range(left, right))
return ans
ā±ļø Time & Space Complexity
-
Time: O(n + m), where
nis the length ofnumsandmis the number of indices added toans - Space: O(m), output list
š§© Key Takeaways
- ā Learned how to efficiently avoid overlap when marking ranges.
- š” Using
rightas a moving pointer to prevent re-adding indices is a smart greedy trick. - š This type of range-based scanning is useful in sliding window and interval problems.
š Reflection (Self-Check)
- [x] Could I solve this without help? ā Yes
- [x] Did I write code from scratch? ā Yes
- [x] Did I understand why it works? ā Yes
- [x] Will I be able to recall this in a week? ā Definitely
š Related Problems
- [[1 Two Sum]]
- [[2817 Minimum Absolute Difference Between Elements With Constraint]]
š Progress Tracker
| Metric | Value |
|---|---|
| Day | 29 |
| Total Problems Solved | 362 |
| Confidence Today | š |
Top comments (0)