Problem 1400

Abstract / Summary

Given a string and an integer k, determine if the string can be split into k or fewer palindrome strings.

Note

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

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
13 lines | 306 bytes | submitted December 8, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (200k+ submissions).

Typical patterns to solve this problem:
  • Counting
  • Greedy
  • Hash Table
  • String
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 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 & 1 eliminates 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 False prevents 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.46 | σ = 1.74

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++ 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++
27 links | 16 authors | 9 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   December 8, 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