Longest Palindrome

Algorithms
Easy
Amazon
123.8K views

Given a string $s$ which consists of lowercase or uppercase letters, find the length of the longest palindrome that can be built from those letters. Case sensitive.

Why Interviewers Ask This

Amazon asks this to evaluate your ability to optimize space complexity while handling edge cases like mixed-case characters. They specifically test if you can recognize that palindrome construction relies on character frequency parity rather than substring continuity, assessing your analytical thinking and efficiency mindset.

How to Answer This Question

1. Clarify constraints: Confirm case sensitivity and whether spaces or special characters exist. 2. Analyze the core logic: Explain that a palindrome needs pairs of identical characters, with at most one unique character allowed in the center. 3. Choose the data structure: Propose using a Hash Map or Frequency Array to count occurrences of each character efficiently. 4. Derive the algorithm: Iterate through counts; add even counts fully, and for odd counts, add (count - 1) to allow pairing, tracking if any odd count exists to add 1 later. 5. Validate edge cases: Discuss scenarios like empty strings or single-character inputs. 6. Optimize: Mention time complexity O(n) and space complexity O(1) due to fixed character set size.

Key Points to Cover

  • Recognizing that character order does not matter, only frequency counts
  • Correctly handling the single-center character rule for odd-length palindromes
  • Distinguishing between uppercase and lowercase as distinct entities
  • Achieving O(n) time complexity with minimal auxiliary space usage
  • Clearly articulating the mathematical logic behind summing even counts and subtracting one from odds

Sample Answer

To solve the longest palindrome problem from a string containing mixed-case letters, I first clarify that since it is case-sensitive, 'A' and 'a' are distinct. The key insight here is that we don't need contiguous substr…

Common Mistakes to Avoid

  • Attempting to find the longest palindromic substring instead of building from available characters
  • Forgetting to handle the single center character when all character counts are odd
  • Ignoring case sensitivity and treating 'A' and 'a' as the same character
  • Using nested loops to compare characters instead of utilizing a hash map for counting

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 145 Algorithms questionsBrowse all 184 Amazon questions