Skip to main content
Back to problems
Leetcode
Medium
Arrays
Sliding Window
Check If All 1s Are At Least Length K Places Away

Determine whether every pair of consecutive 1s in a binary array is separated by at least k zeroes.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

Check If All 1s Are At Least K Places Apart

gfg
Problem Statement

Problem

Given a binary array nums and an integer k, determine whether every pair of consecutive 1 values in the array is separated by at least k positions.

In other words, if two 1s appear at indices i and j with no other 1 between them, then the distance between them must satisfy j - i - 1 >= k.

Return true if this condition holds for the entire array; otherwise return false.

Goal

Check the spacing between all adjacent occurrences of 1 in a single pass or near single-pass manner.

Input Format

  • nums: a binary array of integers containing only 0 and 1
  • k: a non-negative integer

Output Format

  • Return true if all consecutive 1s are at least k places apart
  • Otherwise return false

Constraints

  • 1 <= nums.length
  • nums[i] ∈ {0, 1}
  • k >= 0
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,0,0,0,1,0,0,1], k = 2

Output

true

Explanation

The consecutive 1s are at indices 0, 4, and 7. The gaps between them are 3 and 2, so both are at least 2.

Example 2

Input

nums = [1,0,1], k = 1

Output

false

Explanation

The two 1s are only one position apart, so there are 0 zeroes between them, which is less than 1.

Show 1 more example

Example 3

Input

nums = [0,0,0], k = 2

Output

true

Explanation

There are no pairs of 1s to violate the condition.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.