File: check-if-all-1s-are-at-least-length-k-places-away/solution.py

Date: 2026-06-06

Time: 15:35

Purpose

This file implements the solution to LeetCode 1437: Check If All 1's Are At Least Length K Places Away. It owns exactly one responsibility: given a binary array and an integer k, determine whether every pair of adjacent 1s has at least k zeros between them.

Key Components

Solution.kLengthApart(nums, k) -> bool

The single method on the class. Contract:

Patterns

Sentinel-based last-seen tracking. The variable last is initialized to -1 as a sentinel meaning "no 1 encountered yet." The if last != -1 guard on line 15 skips the distance check for the very first 1, since there's nothing to compare it against. This avoids a separate boolean flag or special first-iteration logic.

Early exit on violation. The method returns False the instant it finds a pair of 1s that are too close, avoiding unnecessary iteration over the rest of the array. The True return at line 17 is only reached if the entire array is scanned without a violation.

Gap arithmetic. The expression i - last - 1 computes the number of elements *strictly between* positions last and i. For example, if 1s are at indices 2 and 5, the gap is 5 - 2 - 1 = 2 (indices 3 and 4). This is compared against k.

Dependencies

Flow

1. Initialize last = -1 (no 1 seen).

2. Iterate over nums with index and value via enumerate.

3. On encountering a 1:

4. If the loop completes without returning False, return True.

Time complexity: O(n) single pass. Space complexity: O(1) — only the last variable is tracked.

Invariants

Error Handling

None. The method assumes valid input per the LeetCode contract (binary array, non-negative k). No exceptions are raised or caught.

Topics to Explore

Beliefs