Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created November 18, 2025 22:00
Show Gist options
  • Select an option

  • Save Ifihan/138d6c330cff263d93e1d86317b99d1b to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/138d6c330cff263d93e1d86317b99d1b to your computer and use it in GitHub Desktop.
Check If All 1's Are at Least Length K Places Away

Question

Approach

I track the index of the previous 1. Each time I see a new 1, I check the distance to the previous one. If the gap is smaller than k, I return False. If all 1s satisfy the distance constraint, I return True

Implementation

class Solution:
    def kLengthApart(self, nums: List[int], k: int) -> bool:
        prev = -1
        
        for i, val in enumerate(nums):
            if val == 1:
                if prev != -1 and i - prev - 1 < k:
                    return False
                prev = i
        
        return True

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment