Cover image for LeetCode daily problem P1437: Are all 1s at least k elements apart?

LeetCode daily problem P1437: Are all 1s at least k elements apart?


Timeline

timeline

2025-11-17

init

array

Problem:

Note: For two positions i and j, the number of elements between them is j-i-1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <vector>
using std::vector;

class Solution {
public:
bool kLengthApart(vector<int> &nums, int k)
{ //Just need to check if adjacent ones are at least k elements apart
int last = -1, i, n = nums.size();
// Find the first 1
for (i = 0; i < n; i++) {
if (nums[i] == 1) {
last = i;
break;
}
}

if (last == -1) {
return true;
}
for (i = last + 1; i < n; i++) {
if (nums[i] == 1) {
if (i - last - 1 < k) {
return false;
} else {
last = i;
}
}
}
return true;
}
};