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
Check If All 1's Are At Least K=2 Places Away1000100101234567Need to check: distance between consecutive 1's > kDistance = 4-0 = 4 > 2 ✓Distance = 7-4 = 3 > 2 ✓Result: trueAll 1's satisfy the k=2 distance requirement
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
Asked in
Facebook 15 Google 12 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen