1437. Check If All 1's Are at Least Length K Places Away #2432
-
|
Topics: Given an binary array Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to determine if all the 1's in a given binary array are at least Approach:
Let's implement this solution in PHP: 1437. Check If All 1's Are at Least Length K Places Away <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Boolean
*/
function kLengthApart($nums, $k) {
$lastOneIndex = -1;
for ($i = 0; $i < count($nums); $i++) {
if ($nums[$i] == 1) {
if ($lastOneIndex != -1 && $i - $lastOneIndex - 1 < $k) {
return false;
}
$lastOneIndex = $i;
}
}
return true;
}
// Test cases
echo kLengthApart([1,0,0,0,1,0,0,1], 2) . "\n"; // Output: true
echo kLengthApart([1,0,0,1,0,1], 2) . "\n"; // Output: false4
?>Explanation:
This approach efficiently checks the required condition in a single pass through the array, ensuring optimal performance with a time complexity of O(n), where n is the length of the input array. The space complexity is O(1) as only a few variables are used. |
Beta Was this translation helpful? Give feedback.


We need to determine if all the 1's in a given binary array are at least
kplaces away from each other. The solution involves iterating through the array, tracking the positions of the 1's, and checking the distance between consecutive 1's to ensure they meet the required separation.Approach:
-1to indicate that no 1 has been encountered yet.lastOneIndexis not-1), we check the distance between the current 1 and the previous 1. The dista…