#3035
Maximum Palindromes After Operations
MediumArrayHash TableStringGreedySortingCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking every swap, we can count the frequency of each character across all words. This allows us to determine how many palindromes can be formed based on character pairs, making the solution efficient.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each character in all words.
- 2Step 2: Calculate the number of pairs of characters that can form palindromes.
- 3Step 3: If there are leftover characters, we can use one of them to form a center of a palindrome.
solution.py12 lines
1def maxPalindromes(words):
2 from collections import Counter
3 freq = Counter()
4 for word in words:
5 freq.update(word)
6 count = 0
7 odd_found = False
8 for ch in freq:
9 count += freq[ch] // 2
10 if freq[ch] % 2 == 1:
11 odd_found = True
12 return count + (1 if odd_found else 0)ℹ
Complexity note: The time complexity is O(n) because we only need to iterate through the words and their characters once to count frequencies, making it linear with respect to the input size.
- 1Character frequency is key to forming palindromes.
- 2Swapping characters can be thought of as redistributing letters to maximize palindrome formation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.