Check If All 1's Are at Least Length K Places Away - Problem

Given a binary array nums and an integer k, determine if all the 1s in the array are positioned such that they are at least k places away from each other.

In other words, for any two 1s at indices i and j, the absolute difference |i - j| should be greater than or equal to k.

Goal: Return true if the spacing condition is satisfied, false otherwise.

Example: In array [1,0,0,0,1,0,0,1] with k=3, the 1s are at indices 0, 4, and 7. The distances are 4-0=4 โ‰ฅ 3 and 7-4=3 โ‰ฅ 3, so return true.

Input & Output

example_1.py โ€” Basic Valid Case
$ Input: nums = [1,0,0,0,1,0,0,1], k = 3
โ€บ Output: true
๐Ÿ’ก Note: The 1s are at indices 0, 4, and 7. Distance between 0 and 4 is 4โ‰ฅ3, distance between 4 and 7 is 3โ‰ฅ3. All conditions satisfied.
example_2.py โ€” Invalid Case
$ Input: nums = [1,0,0,1,0,1], k = 2
โ€บ Output: false
๐Ÿ’ก Note: The 1s are at indices 0, 3, and 5. Distance between 3 and 5 is only 2, but we need at least 2. Since 2 is not > 2, this fails.
example_3.py โ€” Single Element
$ Input: nums = [1], k = 1
โ€บ Output: true
๐Ÿ’ก Note: With only one 1 in the array, there are no pairs to check, so the condition is automatically satisfied.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 0 โ‰ค k โ‰ค nums.length
  • nums[i] is 0 or 1

Visualization

Tap to expand
Social Distancing CheckerMinimum distance: k = 3 positionsQueue Line๐Ÿ‘คPosition 0๐Ÿ‘คPosition 4๐Ÿ‘คPosition 74 units โ‰ฅ 3 โœ“3 units โ‰ฅ 3 โœ“โœ… Social Distancing: COMPLIANTAlgorithm: One-Pass Position Trackingโ€ข Only remember the last person's positionโ€ข Check distance when finding next personTime ComplexityO(n)Space ComplexityO(1)EfficiencyOptimal
Understanding the Visualization
1
Start Walking
Begin at the start of the line with no previous person seen
2
Find First Person
Record the position when we encounter the first person
3
Check Next Person
When we find another person, measure distance from the last one
4
Validate Distance
Ensure the distance meets the minimum requirement
Key Takeaway
๐ŸŽฏ Key Insight: We only need to track the most recent 1's position - no need to store all positions or check all pairs!
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
26.8K Views
Medium Frequency
~12 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