Check If All 1's Are at Least Length K Places Away - Problem
Given a 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.
In other words, check if the distance between any two consecutive 1's in the array is at least k.
Input & Output
Example 1 — Valid Spacing
$
Input:
nums = [1,0,0,0,1,0,0,1], k = 2
›
Output:
true
💡 Note:
All 1's are at least 2 places away: positions [0,4,7], distances are 4-0=4≥2+1 and 7-4=3≥2+1
Example 2 — Invalid Spacing
$
Input:
nums = [1,0,0,1,0,1], k = 2
›
Output:
false
💡 Note:
1's at positions [0,3,5], distance 5-3=2≤k, violates the k=2 minimum distance requirement
Example 3 — Single Element
$
Input:
nums = [1], k = 1
›
Output:
true
💡 Note:
Only one 1 exists, so no distance constraints to check
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ nums[i] ≤ 1
- 1 ≤ k ≤ nums.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
Binary array with 1's that need k-distance validation
2
Process
Check distances between consecutive 1's
3
Output
Return true if all distances > k, false otherwise
Key Takeaway
🎯 Key Insight: Only need to track the previous 1's position and check distance on-the-fly
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code