Sponsored
Sponsored
This approach involves iterating through the array and keeping track of the most recent index where a '1' has been encountered. For every '1' encountered, check if the distance from the last '1' is at least 'k'. If any distance is found to be less than 'k', return false
. If the loop ends without returning false
, return true
.
Time Complexity: O(n), where n is the number of elements in nums.
Space Complexity: O(1), as only a few variables are used.
1function kLengthApart(nums, k) {
2 let lastIndex = -1;
3 for (let i = 0; i < nums.length; i++) {
4 if (nums[i] === 1) {
5 if (lastIndex !== -1 && i - lastIndex - 1 < k) {
6 return false;
7 }
8 lastIndex = i;
9 }
10 }
11 return true;
12}
The JavaScript function leverages a loop to check spaces between '1's, returning false if any two '1's are too close.
This method includes scanning the array to compute gaps between '1's using a counter. If the gap calculated is ever less than k while traversing, return false
. This process continues until the scan ends, signifying all gaps are adequate, thus returning true
.
Time Complexity: O(n), with n being the size of nums array.
Space Complexity: O(1), utilizing constant space to track count.
public bool AreGapsValid(int[] nums, int k) {
int count = k;
foreach (var num in nums) {
if (num == 1) {
if (count < k) return false;
count = 0;
} else {
count++;
}
}
return true;
}
}
This C# solution uses the gap counter technique to confirm that all '1's are distanced by at least k positions within the array.