Practice Check If All 1's Are at Least Length K Places Away
Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.
Problem Statement
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.
Source: Check If All 1's Are at Least Length K Places Away on LeetCode. Use the original task for its coding environment and submissions.
Examples
# Example 1
nums = [1,0,0,0,1,0,0,1], k = 2
true
The 1s occur at zero-based indices 0, 4 and 7. There are 4 - 0 - 1 = 3 zeros between the first pair and 7 - 4 - 1 = 2 between the second pair. Both gaps meet k = 2, so the answer is true. Testing consecutive 1s is sufficient, because any nonconsecutive pair is even farther apart.
# Example 2
nums = [1,0,0,1,0,1], k = 2
false
The 1s are at indices 0, 3 and 5. The first gap contains two zeros and is valid, but the second contains only 5 - 3 - 1 = 1 zero. That violates k = 2, so return false. The index difference is two in that second pair, but one position is occupied by an endpoint; the required zero count is the difference minus one.
Constraints
Related LeetCode Problems
Practice more problems similar to Check If All 1's Are at Least Length K Places Away.
Review your practice with PhantomCodeAI
After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.