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 Places Away INPUT nums array: 0 1 2 3 4 5 6 7 1 0 0 0 1 0 0 1 distance = 4 distance = 3 Input Values: nums = [1,0,0,0,1,0,0,1] k = 2 = Position of 1 = Position of 0 ALGORITHM STEPS 1 Initialize lastPos = -1 (no 1 seen) 2 Scan Array Iterate through each index 3 When 1 Found If lastPos != -1: Check (i - lastPos) > k 4 Update lastPos lastPos = current index Return false if dist <= k Execution Trace: i=0: nums[0]=1, lastPos=-1 lastPos = 0 i=4: nums[4]=1, 4-0=4 > 2 OK i=7: nums[7]=1, 7-4=3 > 2 OK Return true FINAL RESULT All distances verified: 1 at index 0 to 1 at index 4 Distance: 4 > 2 [OK] 1 at index 4 to 1 at index 7 Distance: 3 > 2 [OK] Output: true Verification Complete All consecutive 1's are more than k=2 places apart Condition satisfied! Key Insight: Single Pass O(n) - Track the position of the last seen 1. When a new 1 is found, check if the distance (current index - last position) is greater than k. If any distance is <= k, return false immediately. No need to store all positions - just track the most recent one. Space complexity: O(1). TutorialsPoint - Check If All 1's Are at Least Length K Places Away | Single Pass - Track Last Position
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