πΉ 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 indicesi
such that there exists at least one indexj
where:
nums[j] == key
andabs(i - j) <= k
Return the list of such indices in increasing order.
π§ My Thought Process
-
Brute Force Idea:
- For every index
i
, check every indexj
and see ifnums[j] == key
andabs(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-k
toi+k
are 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
extend
theans
list 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
n
is the length ofnums
andm
is the number of indices added toans
- Space: O(m), output list
π§© Key Takeaways
- β Learned how to efficiently avoid overlap when marking ranges.
- π‘ Using
right
as 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)