Given a string s
and an integer k
, determine if you can construct k
non-empty palindrome strings using all the characters in s
. Return true
if it's possible, and false
otherwise.
Clarifications:
s
be null or empty?k
be zero, negative, or larger than the string's length?Examples:
s = "annabelle", k = 2
true
s = "leetcode", k = 3
false
s = "true", k = 4
true
s = "a", k = 2
false
Constraints:
1 <= s.length <= 10^5
s
consists of lowercase English letters.1 <= k <= 10^5
The brute force approach would involve generating all possible combinations of substrings from the input string s
, and then checking if we can form k
palindromes from these substrings. This approach is highly inefficient due to the combinatorial explosion of possible substring combinations.
s
.This approach is not practical for any reasonably sized input.
A more efficient approach revolves around analyzing the character frequencies in the string s
. The key insight is that a palindrome can be constructed from characters that appear an even number of times. Characters that appear an odd number of times can be at the center of a palindrome. Therefore, the minimum number of palindromes required is equal to the number of characters that appear an odd number of times.
s
.k
, it's impossible to form k
palindromes.k
is greater than the length of s
, it's also impossible as each character would need to be its own palindrome (and string can't be split that way).k
and k
is less than or equal to the string length, it's possible to form k
palindromes.Edge Cases:
s
is empty or null, return false because we need non-empty palindromes.k
is 0, return false as we need to construct non-empty palindromes.k
is 1, check if the entire string can be a palindrome (which is always true if you use all characters).k
is greater than the length of s
, then it's impossible, because each character needs to be its own palindrome.import java.util.HashMap;
import java.util.Map;
class Solution {
public boolean canConstruct(String s, int k) {
if (s == null || s.isEmpty()) {
return false;
}
if (k <= 0) {
return false;
}
if (k > s.length()) {
return false;
}
Map<Character, Integer> charFrequencies = new HashMap<>();
for (char c : s.toCharArray()) {
charFrequencies.put(c, charFrequencies.getOrDefault(c, 0) + 1);
}
int oddCount = 0;
for (int frequency : charFrequencies.values()) {
if (frequency % 2 != 0) {
oddCount++;
}
}
return oddCount <= k;
}
}
s
. This is because we iterate through the string once to count character frequencies and then iterate through the HashMap (which is at most size 26) which is constant time.