Sponsored
Sponsored
This approach involves counting the frequency of each character in the string and calculating the length of the longest possible palindrome based on those frequencies. The key insight is that even frequency counts can completely contribute to a palindrome, while only one odd frequency character can be used once in the center of the palindrome.
Time Complexity: O(n) - where n is the length of the string as we iterate through the string to count character frequencies.
Space Complexity: O(1) - We only use a fixed-size array of 128 elements to store character frequencies.
1def longest_palindrome(s: str) -> int:
2 frequency = {}
3 for char in s:
4 frequency[char] = frequency.get(char, 0) + 1
5 length = 0
6 for count in frequency.values():
7 length += (count // 2) * 2
8 if count % 2 == 1 and length % 2 == 0:
9 length += 1
10 return length
11
12s = "abccccdd"
13print(longest_palindrome(s)) # Output: 7
Python's dictionary allows us to easily count frequencies of each character and then use those frequencies to compute the palindrome's possible largest size by summing pairs and adjusting for any odd center value.
This approach leverages a set data structure to efficiently keep track of characters with odd frequencies. A character encountered an odd number of times will toggle its presence in the set. The result is derived from the total number of characters and the size of this set.
Time Complexity: O(n) - Each character is processed independently.
Space Complexity: O(1) - Fixed memory allocation for set representation.
1
In JavaScript, we employ a Set to toggle character presence, ensuring efficient odd frequency tracking. This influences the final palindrome's computation directly based on the resultant odd set size.