Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

Only consecutive occurrences of one need checking: any more distant pair has at least as much separation. The number of positions between ones at indices previous and i is i - previous - 1, not the raw index difference.

Approach

Scan the array while remembering the last index containing one. On each new one, reject if a previous one exists and the number of intervening positions is below k; then update the remembered index. Return true after the scan. Zero or one occurrence of one satisfies the condition automatically, and k = 0 allows neighboring ones.

class Solution: def kLengthApart(self, nums: List[int], k: int) -> bool: n = len(nums) prev = -1 for i in range(n): if nums[i] == 1: if prev != -1 and i - prev - 1 < k: return False prev = i return True

Complexity analysis

The single index scan takes O(n) time and O(1) auxiliary space.