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.
1#include <vector>
2using namespace std;
3
4class Solution {
5public:
6 bool kLengthApart(vector<int>& nums, int k) {
7 int lastIndex = -1;
8 for (int i = 0; i < nums.size(); i++) {
9 if (nums[i] == 1) {
10 if (lastIndex != -1 && i - lastIndex - 1 < k) {
11 return false;
12 }
13 lastIndex = i;
14 }
15 }
16 return true;
17 }
18};
The solution runs a loop over the vector of integers to track the position of '1'. If two '1's are closer than k positions, it immediately returns false.
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.
This Python method iterates through nums, counting zeros. It verifies each '1' is correctly distanced from its predecessor by checking the counter upon every '1'.