Check If All 1's Are at Least Length K Places Away

Given a binary array `nums` and an integer `k`, return `true` if every pair of `1`s in the array has **at least** `k` places (zeros) between them, and `false` otherwise.

30:00

Check If All 1's Are at Least Length K Places Away
easy
Free written solution
Topics
Companies

Given a binary array nums and an integer k, return true if every pair of 1s in the array has at least k places (zeros) between them, and false otherwise.

Example 1:
Input: {"nums":[1,0,0,0,1,0,0,1],"k":2}
Output: true
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • 0≤k≤nums.length0 \leq k \leq \text{nums.length}

  • nums[i] is 0 or 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,0,0,0,1,0,0,1],"k":2}

Walk left to right remembering where the last 1 was. Each new 1 only has to be at least 2 zeros away from that one.

nums

1
0
0
0
1
0
0
1

0

1

2

3

4

5

6

7

i current index · p last 1 (prev)

zeros between the two 1s vs k

gap

none

0

k

2

measured when the next 1 arrives

Variables
VariableValue
prev-1
k2
DepthFunction Call
Stack empty
0/12