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

The problem requires checking if all 1’s in a binary array are at least k places apart. We can solve it by keeping track of the position of the last 1 we’ve seen. Then for each 1 we encounter, we check if it’s at least k places away from the last one. If we find any pair of 1’s that are less than k places apart, we return False. If we’ve checked all the 1’s and haven’t returned False, it means that all 1’s are at least k places apart, and we return True.

Python solution:

1
2
3
4
5
6
7
8
9
class Solution:
    def kLengthApart(self, nums: List[int], k: int) -> bool:
        last_one = -k - 1
        for i, num in enumerate(nums):
            if num == 1:
                if i - last_one - 1 < k:
                    return False
                last_one = i
        return True

In this code, the variable last_one is initialized to -k - 1 to handle the case when the first element of nums is 1. We then enumerate through nums with i as the index and num as the element. If num is 1, we check if it’s at least k places away from the last one by comparing i - last_one - 1 with k. If it’s less than k, we return False. If it’s at least k, we update last_one to i. If we’ve checked all the elements of nums and haven’t returned False, we return True.