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.
1function longestPalindrome(s) {
2 const frequency = {};
3 for (let char of s) {
4 frequency[char] = (frequency[char] || 0) + 1;
5 }
6 let length = 0;
7 for (let count of Object.values(frequency)) {
8 length += Math.floor(count / 2) * 2;
9 if (count % 2 === 1 && length % 2 === 0) {
10 length++;
11 }
12 }
13 return length;
14}
15
16console.log(longestPalindrome("abccccdd")); // Output: 7;
This JavaScript function uses an object to map character frequencies and then accumulates the largest possible palindrome size, observing the rule of even pairs and a single odd character if applicable.
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
Using Python's set, the solution offers an easy and clear manner to count distinct odd occurrences directly impacting the final outcome for the palindrome computation.