Python 1400.py
class Solution:
def canConstruct(self, s: str, k: int) -> bool:
if k > len(s):
return False
freq = [ 0 ] * 26
for c in s:
freq[ord(c) - ord("a")] += 1
odd = 0
for f in freq:
odd += f & 1
return odd <= k
Difficulty
and has an acceptance rate of about 69% (200k+ submissions).
Typical patterns to solve this problem:
- Counting
- Greedy
- Hash Table
- String
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 a given string s can be partitioned into exactly k non-empty palindromic substrings. The algorithm follows a deterministic sequence: it first validates the relationship between k and the length of s, then builds a frequency table for the characters, counts how many characters appear an odd number of times, and finally checks whether this odd count can be accommodated within the required number of palindromes.
Input Validation
The first conditional guards against an impossible scenario where the number of desired palindromes exceeds the number of characters available. If k is larger than the length of s, the function immediately returns False.
if k > len(s):
return False
This early exit prevents unnecessary work for inputs that cannot possibly satisfy the requirement.
Frequency Table Construction
A fixed-size list of length 26 is allocated to hold the occurrence count of each lowercase English letter. The loop iterates over the characters of s, converting each character to an index by subtracting the ASCII code of 'a'. The corresponding slot in freq is incremented.
freq = [0] * 26
for c in s:
freq[ord(c) - ord('a')] += 1
Using a pre-allocated array avoids the overhead of dynamic structures such as dictionaries, and the direct index calculation ensures constant-time updates.
Counting Odd Frequencies
The algorithm computes how many character counts are odd. It iterates over the frequency array and accumulates the result of a bitwise AND between each count and 1. The expression f & 1 yields 1 for odd numbers and 0 for even numbers, allowing a compact accumulation without branching.
odd = 0
for f in freq:
odd += f & 1
This technique leverages low-level bit operations for speed, especially beneficial when the loop runs over a small, fixed size (26 elements).
Final Feasibility Check
A palindrome can accommodate at most one character with an odd count (as the central element). Consequently, the minimum number of palindromes required equals the number of odd counts. The function returns True when the available k palindromes are at least as many as the odd count.
return odd <= k
This single comparison encapsulates the core logical condition of the problem.
Edge Cases Handled
When s is empty, the frequency table remains all zeros, resulting in odd equal to 0. The early validation step ensures that k must also be 0 for the function to return True; otherwise, it returns False. This correctly reflects that no palindromes can be formed from an empty string unless zero palindromes are requested.
If k equals the length of s, each character must become its own palindrome. The early validation permits this scenario because k is not greater than len(s). The frequency counting will produce an odd count equal to the number of distinct characters that appear an odd number of times. Since each character can serve as a single-character palindrome, the final comparison odd <= k will hold, yielding True.
When all characters in s are identical, the frequency table contains a single non-zero entry. The odd count will be 1 if the total length is odd, or 0 if even. The function therefore permits any k that is at least this odd count, correctly allowing the string to be split into the requested number of palindromes.
Performance Optimizations
The implementation exhibits several deliberate choices aimed at minimizing runtime overhead:
- Fixed-size array for frequencies: By allocating a list of 26 integers, the code avoids hash-based lookups and dynamic resizing, leading to predictable memory access patterns.
- Bitwise odd detection: Using
f & 1eliminates conditional branches that would be required with modulo operations, resulting in faster execution on modern CPUs. - Early exit on impossible input: The check
if k > len(s): return Falseprevents the algorithm from performing any further work when the answer is known a priori. - Single pass over the string: The frequency counting loop processes each character exactly once, ensuring linear time relative to the input size.
- Compact final comparison: The result is derived from a single integer comparison, avoiding additional loops or data structures.
These optimizations collectively ensure that the function runs efficiently even for large strings, while maintaining clarity and correctness.
ELI5 - Simplified Explanation
Imagine you have a big bucket full of different colored Lego bricks. The letters in the word are like those bricks. You want to see if you can build exactly a certain number of towers using every single brick.
First, check if you have enough bricks to make those towers. If you need more towers than the total number of bricks, it is impossible because some towers would be empty.
Next, count how many of each color you have. When building towers, if you want a tower to be a matching pair, you need two bricks of the same color. But if you have an odd number of a specific color, like having three blue bricks, you can use two to make a pair and one extra blue brick has to be the top of a tower all by itself.
The code looks at all the colors and counts how many colors have an odd number of bricks. Each of those leftover bricks must be the top of its own individual tower. As long as the number of towers you need to build is at least as big as the number of those lonely leftover bricks, you can finish your project perfectly.
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++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Python | Go | TS | |||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| Shamik07 | Dart | |||||||||
| varunu28 | Java | |||||||||
| withaarzoo | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| Shamik07 | Dart | |||||||||
| varunu28 | Java | |||||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 1442: Count Triplets That Can Form Two Arrays of Equal XOR
- problem 1519: Number of Nodes in the Sub-Tree With the Same Label
- problem 1577: Number of Ways Where Square of Number Is Equal to Product of Two Numbers
- problem 1593: Split a String Into the Max Number of Unique Substrings
- problem 1604: Alert Using Same Key-Card Three or More Times in a One Hour Period
- problem 1638: Count Substrings That Differ by One Character
- problem 1695: Maximum Erasure Value
- problem 1726: Tuple with Same Product
- problem 1368: Minimum Cost to Make at Least One Valid Path in a Grid
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