I track the index of the previous 1. Each time I see a new 1, I check the distance to the previous one. If the gap is smaller than k, I return False. If all 1s satisfy the distance constraint, I return True
class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
prev = -1
for i, val in enumerate(nums):
if val == 1:
if prev != -1 and i - prev - 1 < k:
return False
prev = i
return True- Time: O(n)
- Space: O(1)