Post

1548 Check If All 1S Are At Least Length K Places Away

1548 Check If All 1S Are At Least Length K Places Away

Check If All 1’s Are at Least Length K Places Away image

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.

 

Example 1:

image

1
2
3
4
5
**Input:** nums = [1,0,0,0,1,0,0,1], k = 2
**Output:** true
**Explanation:** Each of the 1s are at least 2 places away from each other.

Example 2:

image

1
2
3
4
5
**Input:** nums = [1,0,0,1,0,1], k = 2
**Output:** false
**Explanation:** The second 1 and third 1 are only one apart from each other.

 

Constraints:

1
2
3
1 <= nums.length <= 105
0 <= k <= nums.length
nums[i] is 0 or 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

impl Solution {
    pub fn k_length_apart(nums: Vec<i32>, k: i32) -> bool {
        let mut diff = -1;

        for m in nums {
            if diff == -1 && m == 0 {
                continue;
            }

            if diff == -1 && m == 1 {
                diff = 0;
                continue;
            }

            if m == 0 {
                
                diff += 1;
            } else {
                if diff < k {
                    
                    return false;
                } else {
                    diff = 0;
                }
            }
        }
        return true;
    }
}



This post is licensed under CC BY 4.0 by the author.