Problem 1437

Abstract / Summary

Check if a string can be rearranged into a palindrome by verifying at most one character has an odd count.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1437.py

class Solution:
    def kLengthApart(self, nums: List[int], k: int) -> bool:
        streak  = 0
        padding = [ 0 ] * k
        for n in padding + nums + padding:
            if n == 0:
                streak += 1
            else: # n == 1
                if streak < k:
                    return False
                streak  = 0

        return True
13 lines | 372 bytes | submitted December 16, 2023 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation determines whether all occurrences of the value 1 in a binary list are separated by at least k zeros. It does so by scanning the list once, while implicitly handling the boundaries of the input through a padding technique. The algorithm returns True when the distance condition holds for the entire sequence, otherwise it returns False as soon as a violation is detected.

Core Logic

Initialization

The method begins by creating two auxiliary variables.

streak  = 0
padding = [0] * k

streak counts consecutive zeros encountered during the scan. padding is a list of k zeros that will be placed before and after the original data. This padding guarantees that the first and last 1 are evaluated with the same logic as interior 1s, eliminating the need for special-case checks at the ends of the array.

Unified Traversal

The algorithm concatenates the padding, the input list, and another copy of the padding, then iterates over the combined sequence.

for n in padding + nums + padding:
    if n == 0:
        streak += 1
    else:  # n == 1
        if streak < k:
            return False
        streak = 0

During each iteration the current element n is examined. If it is a zero, the streak counter is incremented. When a one is encountered, the current streak value represents the number of zeros that preceded this one. The algorithm checks whether that count meets the required minimum k. If the count is insufficient, the function aborts early with False. Otherwise the counter is reset to start measuring the gap before the next one.

Final Result

If the loop completes without triggering a failure, the method returns True, indicating that every pair of ones is separated by at least k zeros.

return True

Edge Cases Handled

The padding approach automatically covers several boundary conditions:

  • Empty input - When nums is empty, the loop processes only the padding. No 1 is encountered, so the function reaches the final return True, correctly indicating that the condition holds vacuously.
  • Single element - If the list contains a single 1, the preceding padding supplies at least k zeros, allowing the check streak < k to succeed and the function to return True.
  • All zeros - The loop never encounters a 1; streak simply grows, and the function returns True after the full pass, which is the expected outcome because there are no pairs of ones to violate the distance rule.
  • All ones - The first padded zeroes provide a streak of k before the first real 1. After resetting, the next immediate 1 will see a streak of 0, causing the early return False. This correctly flags the violation.
  • Zero distance requirement (k == 0) - The padding list becomes empty, and the condition streak < k is never true because k is zero. Consequently, the function accepts any arrangement of ones, matching the definition that no separation is required.

Performance Optimizations

The implementation exhibits several deliberate choices that improve runtime efficiency:

  • Single pass with early exit - By returning immediately when a gap smaller than k is found, the algorithm avoids unnecessary processing of the remainder of the list.
  • In-place counter - The use of a simple integer streak avoids allocating additional data structures for tracking positions of ones, keeping the memory footprint minimal.
  • Padding to simplify logic - Adding k zeros at both ends removes the need for separate conditional branches for the first and last elements. This reduces branch misprediction overhead and keeps the loop body uniform.
  • Concatenation of small lists - The padding lists are created once and reused in the concatenation, which Python implements efficiently for short sequences. The overall loop still processes each element exactly once.

These characteristics ensure that the method runs quickly even for large input arrays while maintaining a clear and concise code path.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a very long line of toy blocks laid out on the floor. Some blocks are the number one and some blocks are the number zero. There is a special rule that says every time a number one appears, there must be at least a certain number of spaces filled with the number zero before the next number one can show up.

To keep track of this, think of a little counter that counts how many zero blocks have been seen in a row. Every time a zero block shows up, the counter gets bigger by one. Whenever a number one block shows up, the rules are checked. If the counter is too small, that means the number ones are sitting too close to each other, which breaks the rule. If the number ones are far enough apart, the counter gets reset back to zero so it can start counting for the next set of blocks. The extra zero blocks added to the beginning and the end make sure the rule stays true for the ones at the very start and the very end of the line.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.52 | σ = 1.52

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC Python
leetcode.ca C++ Python Java Go Rust TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
fartem Ruby
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
withaarzoo C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC Python
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
fartem Ruby
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
withaarzoo C++
YuriSpiridonov Python
29 links | 19 authors | 10 languages

Solved On The Same Day

5 solutions   December 16, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality