|
| 1 | +# [Problem 1437: Check If All 1's Are at Least Length K Places Away](https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/description/?envType=daily-question) |
| 2 | + |
| 3 | +## Initial thoughts (stream-of-consciousness) |
| 4 | +I need to verify that every pair of 1s in the array has at least k zeros between them. The array length up to 1e5 so an O(n) scan is fine. The simplest idea: walk the array, remember the index of the previous 1; when I encounter a new 1, compute the gap between indices and check whether there are at least k zeros between them. If any gap is too small, return False. If I finish the scan, return True. |
| 5 | + |
| 6 | +Edge quick thoughts: if k == 0 it's always true because no separation required. For the first encountered 1 there is no previous to compare with. Use -inf or None to indicate no previous 1. Be careful with off-by-one: if previous 1 at i_prev and current at i, number of places between = i - i_prev - 1, so require i - i_prev - 1 >= k -> equivalently i - i_prev > k. |
| 7 | + |
| 8 | +## Refining the problem, round 2 thoughts |
| 9 | +Implementation details: |
| 10 | +- Iterate with enumerate to get indices. |
| 11 | +- Keep prev index initialized to None. |
| 12 | +- On nums[i] == 1: |
| 13 | + - If prev is not None, check if i - prev - 1 < k -> return False. |
| 14 | + - Update prev = i. |
| 15 | +- Complexity: single pass, O(n) time, O(1) extra space. |
| 16 | +Alternative approaches: you could count consecutive zeros after each 1, or use a queue to store last 1s, but those are no simpler or not more efficient in this problem. |
| 17 | + |
| 18 | +Edge cases: |
| 19 | +- All zeros -> True. |
| 20 | +- Single 1 -> True. |
| 21 | +- k = 0 -> True. |
| 22 | +- Adjacent 1s -> must be k = 0 to be valid. |
| 23 | + |
| 24 | +## Attempted solution(s) |
| 25 | +```python |
| 26 | +from typing import List |
| 27 | + |
| 28 | +class Solution: |
| 29 | + def kLengthApart(self, nums: List[int], k: int) -> bool: |
| 30 | + prev = None # index of previous 1 |
| 31 | + for i, val in enumerate(nums): |
| 32 | + if val == 1: |
| 33 | + if prev is not None: |
| 34 | + # number of places between prev and i is (i - prev - 1) |
| 35 | + if i - prev - 1 < k: |
| 36 | + return False |
| 37 | + prev = i |
| 38 | + return True |
| 39 | +``` |
| 40 | +- Notes: |
| 41 | + - Approach: single pass keeping the index of the last seen 1 and checking the number of zeros between consecutive 1s. |
| 42 | + - Time complexity: O(n), where n = len(nums), because we examine each element once. |
| 43 | + - Space complexity: O(1) extra space (only an index variable). |
| 44 | + - Implementation detail: the check uses i - prev - 1 < k (equivalently i - prev <= k) to detect a violation. |
0 commit comments