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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code