Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check whether we can make k palindromes from given string characters or not in Python?
Suppose we have a string s and another number k, we have to check whether we can create k palindromes using all characters in s or not.
So, if the input is like s = "amledavmel" k = 2, then the output will be True, as we can make "level" and "madam".
Algorithm
To solve this, we will follow these steps ?
d := a map where store each unique characters and their frequency
cnt := 0
-
for each key in d, do
-
if d[key] is odd, then
cnt := cnt + 1
-
if cnt > k, then
return False
-
return True
How It Works
The key insight is that for a palindrome, at most one character can have an odd frequency (the middle character). If we have more odd-frequency characters than k, we cannot form k palindromes.
Example
Let us see the following implementation to get better understanding ?
from collections import Counter
class Solution:
def solve(self, s, k):
d = Counter(s)
cnt = 0
for key in d:
if d[key] & 1:
cnt += 1
if cnt > k:
return False
return True
ob = Solution()
s = "amledavmel"
k = 2
print(ob.solve(s, k))
The output of the above code is ?
True
Step-by-Step Execution
For string "amledavmel" with k = 2 ?
from collections import Counter
s = "amledavmel"
k = 2
# Count character frequencies
char_count = Counter(s)
print("Character frequencies:", char_count)
# Count characters with odd frequency
odd_count = 0
for char, freq in char_count.items():
if freq % 2 == 1:
odd_count += 1
print(f"'{char}' has odd frequency: {freq}")
print(f"Total odd frequency characters: {odd_count}")
print(f"Can form {k} palindromes: {odd_count <= k}")
Character frequencies: Counter({'a': 2, 'm': 2, 'l': 2, 'e': 2, 'd': 1, 'v': 1})
'd' has odd frequency: 1
'v' has odd frequency: 1
Total odd frequency characters: 2
Can form 2 palindromes: True
Key Points
Each palindrome can have at most one character with odd frequency (the middle character)
If odd frequency characters exceed k, we cannot form k palindromes
Characters with even frequencies can be split evenly across palindromes
Conclusion
To check if k palindromes can be formed from a string, count characters with odd frequencies. If this count is ? k, then k palindromes are possible since each palindrome can accommodate at most one odd-frequency character.
