You are given an integer array nums
representing a binary array, and an integer k
.
Return True
if all 1's
are at least k
places away from each other, otherwise return False
.
Input: nums = [1,0,0,0,1,0,0,1], k = 2
Output: True
Input: nums = [1,0,0,1,0,1], k = 2
Output: False
1 <= nums.length <= 10^5
0 <= k <= nums.length - 1
nums[i]
is either 0
or 1
.0
and 1
?
nums
is a binary array.1 <= nums.length
.k
is 0
, i.e., the required spacing is zero?
True
since no spacing is required between 1
s.To solve this problem, we can iterate through the array and keep track of the index of the last encountered 1
. For each new 1
we encounter, we check the distance from the previous 1
. If the distance is less than k
, we return False
. If we complete the iteration without finding any 1
s that are too close, we return True
.
def kLengthApart(nums: list[int], k: int) -> bool:
last_position = -1 # Initialize to -1 which indicates no 1 has been found yet.
for i in range(len(nums)):
if nums[i] == 1:
if last_position != -1 and i - last_position - 1 < k:
return False
last_position = i
return True
# Test Cases
print(kLengthApart([1, 0, 0, 0, 1, 0, 0, 1], 2)) # True
print(kLengthApart([1, 0, 0, 1, 0, 1], 2)) # False
print(kLengthApart([1, 1, 1, 1, 1], 0)) # True
print(kLengthApart([0, 1, 0, 0, 0, 1, 0, 0, 1, 0], 2)) # True
The time complexity of this solution is ( O(n) ) where ( n ) is the length of the nums
array. This is because we are iterating through the array once.
The space complexity is ( O(1) ) because we only use a few extra variables regardless of the input size.
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?