[
array
]
Leetcode 1437. Check If All 1s Are at Least Length K Places Away
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away
Easy problem, we just need to iterate over numbers and keep distance dist
to the last occurence of 1
.
- If we meet
0
, we need to increase distance by1
. - If we meet
1
and current distance is more or equal thank
, than everything is OK and we need to updatedist = 0
. - If we meet
1
and current distance is less thank
, than there will be two1
placed less thank
indexes away, so we can immedietly returnFalse
. - In the end we return
True
if we reached this place.
Complexity: time complexity is O(n)
to pass over our data once, space comlexity is O(1)
.
class Solution:
def kLengthApart(self, nums, k):
dist = k
for num in nums:
if num == 0: dist += 1
elif num == 1 and dist >= k: dist = 0
else: return False
return True
If you like the solution, you can upvote it on leetcode discussion section: Problem 1437