Leetcode 1437. Check If All 1’s Are at Least Length K Places Away
You are 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
.
nums = [1,0,0,0,1,0,0,1]
, k = 2
Output: true
nums = [1,0,0,1,0,1]
, k = 2
Output: false
nums
and k
?
nums
can range from 2 to 10^5.k
is a non-negative integer and will be less than or equal to the length of nums
.k
that are greater than the length of nums
.previousIndex
to keep track of the index of the last 1 encountered.nums
array:
previousIndex
.k
, return false
.previousIndex
to the current index.true
.public class Solution {
public boolean kLengthApart(int[] nums, int k) {
int previousIndex = -1; // Initially no 1 encountered
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
if (previousIndex != -1 && i - previousIndex - 1 < k) {
return false; // Distance between the current 1 and the previous 1 is less than k
}
previousIndex = i; // Update previousIndex to the current index
}
}
return true;
}
}
n
is the length of the nums
array as we have to scan the entire array once.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?