Check If All 1's Are at Least Length K Places Away Problem
#1437
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1437.
Given an binary array nums and an integer k, return true if all 1's are at least k places away from each other, otherwise return false.
Example 1:

Input: nums = [1,0,0,0,1,0,0,1], k = 2
Output: true
Explanation: Each of the 1s are at least 2 places away from each other.
Example 2:

Input: nums = [1,0,0,1,0,1], k = 2
Output: false
Explanation: The second 1 and third 1 are only one apart from each other.
Constraints:
1 <= nums.length <= 10^50 <= k <= nums.lengthnums[i]is0or1
Solution
Approach: Remember the Previous 1
Scan the array and keep last, the index of the previous 1 (or -1 before the first one). At each new 1 at index i, the number of places between the two ones is i - last - 1. If that is less than k, return false; otherwise set last = i and go on.
Only neighbouring ones need checking: if every pair of consecutive ones is far enough apart, any two ones further apart are too. The first 1 has nothing to compare with, which is why last starts at -1 and is skipped. With k = 0, any arrangement is valid.
Complexity: O(n) time and O(1) extra space.
class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
last = -1 # index of the previous 1, or -1 before the first one
for i, x in enumerate(nums):
if x == 1:
# i - last - 1 zeros sit between this 1 and the previous one
if last != -1 and i - last - 1 < k:
return False
last = i
return True