Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Longest Palindrome

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "409" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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.

Explanation

Here's the solution to the problem, adhering to the specified format:

  • High-Level Approach:

    • Count the frequency of each character in the string.
    • For each character, use an even number of occurrences to build the palindrome (e.g., if 'c' occurs 4 times, use all 4).
    • If there's any character with an odd number of occurrences, use one of those characters in the center of the palindrome to maximize its length.
  • Complexity:

    • Runtime Complexity: O(n), where n is the length of the string.
    • Storage Complexity: O(1), because the character frequency dictionary will store at most 52 unique characters (26 lowercase and 26 uppercase).

Code

    def longestPalindrome(s: str) -> int:
    """
    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.
    """

    char_counts = {}
    for char in s:
        char_counts[char] = char_counts.get(char, 0) + 1

    length = 0
    odd_count_exists = False
    for count in char_counts.values():
        if count % 2 == 0:
            length += count
        else:
            length += count - 1
            odd_count_exists = True

    if odd_count_exists:
        length += 1

    return length

More from this blog

C

Chatmagic blog

2894 posts