##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1437.html

# 1437. Check If All 1’s Are at Least Length K Places Away (Medium)

Given an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False.

Example 1:

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:

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.

Example 3:

Input: nums = [1,1,1,1,1], k = 0
Output: true


Example 4:

Input: nums = [0,1,0,1], k = 1
Output: true


Constraints:

• 1 <= nums.length <= 10^5
• 0 <= k <= nums.length
• nums[i] is 0 or 1

Related Topics:
Array

## Solution 1.

• class Solution {
public boolean kLengthApart(int[] nums, int k) {
if (k == 0)
return true;
int length = nums.length;
int prevOneIndex = -k - 1;
for (int i = 0; i < length; i++) {
if (nums[i] == 1) {
if (i - prevOneIndex <= k)
return false;
prevOneIndex = i;
}
}
return true;
}
}

############

class Solution {
public boolean kLengthApart(int[] nums, int k) {
int j = -1;
for (int i = 0; i < nums.length; ++i) {
if (nums[i] == 1) {
if (j != -1 && i - j - 1 < k) {
return false;
}
j = i;
}
}
return true;
}
}

• // OJ: https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/
// Time: O(N)
// Space: O(1)
class Solution {
public:
bool kLengthApart(vector<int>& A, int k) {
int prev = -k - 1;
for (int i = 0; i < A.size(); ++i) {
if (A[i] == 0) continue;
if (i - prev <= k) return false;
prev = i;
}
return true;
}
};

• class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
j = -1
for i, v in enumerate(nums):
if v == 1:
if j > -1 and i - j - 1 < k:
return False
j = i
return True

############

class Solution(object):
def kLengthApart(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
left_1 = float("-inf")
for i, num in enumerate(nums):
if num == 1:
if i - left_1 < k + 1:
return False
left_1 = i
return True

• func kLengthApart(nums []int, k int) bool {
j := -1
for i, v := range nums {
if v == 1 {
if j != -1 && i-j-1 < k {
return false
}
j = i
}
}
return true
}

• function kLengthApart(nums: number[], k: number): boolean {
let j = -(k + 1);
for (let i = 0; i < nums.length; ++i) {
if (nums[i] === 1) {
if (i - j - 1 < k) {
return false;
}
j = i;
}
}
return true;
}