Skip to content

Commit 9cfc9aa

Browse files
authored
Create find-all-k-distant-indices-in-an-array.py
1 parent f2a6829 commit 9cfc9aa

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# two pointers
5+
class Solution(object):
6+
def findKDistantIndices(self, nums, key, k):
7+
"""
8+
:type nums: List[int]
9+
:type key: int
10+
:type k: int
11+
:rtype: List[int]
12+
"""
13+
result = []
14+
prev = -1
15+
for i, x in enumerate(nums):
16+
if x != key:
17+
continue
18+
for j in xrange(max(i-k, prev+1), min(i+k+1, len(nums))):
19+
result.append(j)
20+
prev = min(i+k, len(nums)-1)
21+
return result

0 commit comments

Comments
 (0)