Taro Logo

Longest Palindrome

#1 Most AskedEasy
0 views
Topics:
StringsGreedy Algorithms

Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.

Letters are case sensitive, for example, "Aa" is not considered a palindrome.

Example 1:

Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.

Example 2:

Input: s = "a"
Output: 1
Explanation: The longest palindrome that can be built is "a", whose length is 1.

Constraints:

  • 1 <= s.length <= 2000
  • s consists of lowercase and/or uppercase English letters only.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are the letters in the string case-sensitive, meaning 'A' and 'a' should be treated as distinct characters?
  2. Can the input string be empty, and if so, should the expected return length be 0?
  3. Do the characters we use to build the palindrome have to form a contiguous substring from the original string, or can we pick and choose characters from anywhere in the string?
  4. What is the maximum length of the input string s that we need to support?
  5. If multiple palindromes of the maximum possible length can be formed, does it matter which one's length is returned, or are they all guaranteed to have the same maximum length?

Brute Force Solution

Approach

When trying to find the longest palindrome that can be built from a collection of letters, the brute force approach is like testing every possible combination of letters to see which ones spell the same thing forwards and backwards. We exhaustively explore all ways to arrange the available letters and measure how long each successful symmetrical word turns out to be.

Here's how the algorithm would work step-by-step:

  1. Start by looking at all the individual letters you are given.
  2. Try making every possible sequence and arrangement using these letters, from groups of single letters all the way up to using every single letter provided.
  3. For every sequence you create, check if it reads the exact same way forwards and backwards.
  4. Discard any arrangement that does not read the same way in both directions.
  5. Keep a mental note of all the valid symmetrical arrangements that you successfully discover.
  6. Compare the lengths of all the valid symmetrical arrangements you found.
  7. Select the one with the maximum length as your final answer.

Code Implementation

import itertools


def longest_palindrome_brute_force(input_string):
    maximum_length = 0
    
    # Generate all possible lengths and letter arrangements to find any hidden palindromes
    for current_length in range(1, len(input_string) + 1):
        for current_perm in itertools.permutations(input_string, current_length):
            
            # Convert the tuple of characters back into a string for palindrome testing
            candidate_string = ''.join(current_perm)
            
            # Verify symmetry to ensure the candidate actually reads the same backwards
            if candidate_string == candidate_string[::-1]:
                maximum_length = max(maximum_length, len(candidate_string))
                
    return maximum_length

Big(O) Analysis

Time Complexity
O(n! * n) – To find the longest palindrome using the brute force approach, we must generate every possible permutation of the n input characters, resulting in n! different arrangements. For each of these n! arrangements, we iterate through its characters to check if it reads the same forwards and backwards, which takes an additional n steps per sequence. This leads to approximately n! * n total operations. Therefore, the time complexity simplifies to O(n! * n).
Space Complexity
O(k) – The brute force approach requires generating permutations and storing valid symmetrical arrangements in memory to compare their lengths. As the input size N grows, the number of possible permutations and intermediate valid sequences stored temporarily can scale significantly. Specifically, the data structures used to track and measure every valid symmetrical arrangement consume extra memory proportional to the number of unique characters or the maximum possible palindrome length K. Therefore, the auxiliary space complexity simplifies to O(k), where K represents the size of the character set or the bound of valid arrangements.

Optimal Solution

Approach

To find the longest possible palindrome you can build, the optimal approach focuses on counting how many times each letter appears. Since a palindrome is symmetrical, you can use pairs of matching letters on both sides and optionally place one leftover letter right in the middle.

Here's how the algorithm would work step-by-step:

  1. Go through the entire collection of letters and keep a tally of how many times each specific letter shows up.
  2. Review the tallies for every letter to see how many complete pairs you can form.
  3. Add up all the complete pairs because every pair contributes two matching letters to your growing palindrome, one for each side.
  4. Check if you have any leftover letters that could not be paired up.
  5. If you found at least one leftover letter, you can place one of them right in the middle of your palindrome as a single unmatched character.
  6. Combine all your pairs and the optional middle letter to determine the maximum possible length for your palindrome.

Code Implementation

from collections import Counter


def longest_palindrome(input_string):
    # We count frequencies to determine how many matching character pairs we can form.
    letter_frequency_map = Counter(input_string)
    
    palindrome_length = 0
    has_odd_frequency = False

    for frequency_count in letter_frequency_map.values():
        # Even counts contribute fully to pairs, while odd counts contribute all-but-one.
        palindrome_length += frequency_count // 2 * 2
        
        if frequency_count % 2 == 1:
            has_odd_frequency = True

    # A single unmatched character can be placed in the center of the palindrome.
    if has_odd_frequency:
        palindrome_length += 1

    return palindrome_length

Big(O) Analysis

Time Complexity
O(n) – To analyze the time complexity, let n be the length of the string containing the collection of letters. First, we iterate through the entire string of size n once to tally the frequency of each specific letter. Next, we iterate through the fixed-size frequency table to sum up the complete pairs and check for any leftovers. Since the second step processes a constant number of possible characters regardless of n, the total operations are driven by the initial pass of size n. This results in approximately 1 * n operations, which simplifies to O(n).
Space Complexity
O(1) – The auxiliary space is driven by a hash map or frequency array used to tally the occurrences of each letter. Because the character set is strictly limited to standard alphabetic characters like uppercase and lowercase English letters, the maximum number of unique keys stored is at most 52. Therefore, the extra memory required remains constant regardless of the input string length N, resulting in an O(1) space complexity.

Edge Cases

Empty string input
How to Handle:
Return zero immediately since no palindrome can be formed from zero characters.
Single character string
How to Handle:
Return one because a single character is technically a valid palindrome of length one.
String with all unique characters
How to Handle:
Return one since only a single character can be placed in the middle as an odd-frequency element.
String with all identical characters
How to Handle:
Return the exact length of the string because all characters can be paired up symmetrically.
Mixed case letters
How to Handle:
Treat uppercase and lowercase letters as distinct characters by using their exact ASCII or Unicode values in our frequency count.
All character counts are even
How to Handle:
Sum all frequencies entirely without adding one since no middle character is needed.
Maximum constraint string length
How to Handle:
Process the string in linear time using a hash map or frequency array to scale efficiently without exceeding memory or time limits.
0/1 completed