Determine whether every pair of consecutive 1s in a binary array is separated by at least k zeroes.
Check If All 1s Are At Least K Places Apart
gfgProblem
Given a binary array nums and an integer k, determine whether every pair of consecutive 1 values in the array is separated by at least k positions.
In other words, if two 1s appear at indices i and j with no other 1 between them, then the distance between them must satisfy j - i - 1 >= k.
Return true if this condition holds for the entire array; otherwise return false.
Goal
Check the spacing between all adjacent occurrences of 1 in a single pass or near single-pass manner.
Input Format
nums: a binary array of integers containing only0and1k: a non-negative integer
Output Format
- Return
trueif all consecutive1s are at leastkplaces apart - Otherwise return
false
Constraints
1 <= nums.lengthnums[i] ∈ {0, 1}k >= 0
Example 1
Input
nums = [1,0,0,0,1,0,0,1], k = 2
Output
true
Explanation
The consecutive 1s are at indices 0, 4, and 7. The gaps between them are 3 and 2, so both are at least 2.
Example 2
Input
nums = [1,0,1], k = 1
Output
false
Explanation
The two 1s are only one position apart, so there are 0 zeroes between them, which is less than 1.
Show 1 more example
Example 3
Input
nums = [0,0,0], k = 2
Output
true
Explanation
There are no pairs of 1s to violate the condition.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.