Back to posts

LeetCode Challenge Day 63 β€” 1437. Check If All 1's Are at Least Length K Places Away

Nitin Ahirwal / November 17, 2025

LeetCode ChallengeDay 63Binary ArrayGreedyJavaScriptEasy

Hey folks πŸ‘‹

This is Day 63 of my LeetCode streak πŸš€
Today’s problem is 1437 β€” Check If All 1's Are at Least Length K Places Away.

A clean and efficient check:
Make sure every pair of 1s in the binary array has at least k zeros between them.


πŸ’‘ Intuition

The idea is simple:

Whenever we encounter a 1, we only need to check how far it is from the previous 1.

  • If the gap is less than k, return false
  • Otherwise, update the last-seen position

This avoids scanning extra ranges or constructing substrings β€” just a distance check.


πŸ“Œ Approach

  1. Start with prev = -k - 1 so the first 1 always passes the check.
  2. Traverse the array:
    • When you see a 1 at index i:
      • Check if i - prev - 1 < k
      • If true β†’ not enough zeros β†’ return false
      • Else, update prev = i
  3. If no violations occur, return true.

A single left-to-right pass solves it.


πŸ“ˆ Complexity

  • Time Complexity: O(n) β€” one scan
  • Space Complexity: O(1) β€” constant extra space

πŸ§‘β€πŸ’» Code (JavaScript)

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {boolean}
 */
var kLengthApart = function(nums, k) {
    // prev initialized so the first 1 always passes the check
    let prev = -k - 1;
    
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] === 1) {
            if (i - prev - 1 < k) return false;
            prev = i;
        }
    }
    return true;
};

🎯 Example

Input:
nums = [1,0,0,0,1,0,0], k = 2
Output:
true

Because the distance between the two 1s is exactly 3 β†’ satisfies k = 2.


🧠 Reflection

This problem highlights how a single pointer and a simple invariant can solve what looks like a spacing constraint problem.

Key takeaways:

  • Track what matters (the last seen 1)

  • Validate only the required condition

  • Avoid extra data structures

See you tomorrow for Day 64! πŸš€
Happy Coding πŸ‘¨β€πŸ’»βœ¨