#1437
Easy Algorithms Check if all 1s are at least length k places away
Array
64.3% acceptance
Feb 25, 2026
957
243
Given an 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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn k_length_apart(nums: Vec<i32>, k: i32) -> bool {
let mut last_one: Option<usize> = None;
for (i, &n) in nums.iter().enumerate() {
if n == 1 {
if let Some(prev) = last_one {
if i - prev - 1 < k as usize { return false; }
}
last_one = Some(i);
}
}
true
}
}