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
Difficulty
and has an acceptance rate of about 64% (300k+ submissions).
Typical patterns to solve this problem:
- Array
AI Disclaimer
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.
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
numsis empty, the loop processes only the padding. No1is encountered, so the function reaches the finalreturn True, correctly indicating that the condition holds vacuously. - Single element - If the list contains a single
1, the preceding padding supplies at leastkzeros, allowing the checkstreak < kto succeed and the function to returnTrue. - All zeros - The loop never encounters a
1;streaksimply grows, and the function returnsTrueafter 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
streakofkbefore the first real1. After resetting, the next immediate1will see astreakof0, causing the earlyreturn False. This correctly flags the violation. - Zero distance requirement (
k == 0) - The padding list becomes empty, and the conditionstreak < kis never true becausekis 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
kis found, the algorithm avoids unnecessary processing of the remainder of the list. - In-place counter - The use of a simple integer
streakavoids allocating additional data structures for tracking positions of ones, keeping the memory footprint minimal. - Padding to simplify logic - Adding
kzeros 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Solved On The Same Day
- problem 1422: Maximum Score After Splitting a String
- problem 1560: Most Visited Sector in a Circular Track
- problem 2269: Find the K-Beauty of a Number
- problem 2379: Minimum Recolors to Get K Consecutive Black Blocks
Extra
- 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