Program to find length of longest anagram subsequence in Python

In Python, a string is an immutable data structure in which sequence of characters are enclosed in double("") or single quotes(''). In some cases, we need to find the length of the longest subsequence of characters that can be rearranged to form a palindrome. This type of subsequence is referred to as a palindromic anagram subsequence.

An anagram is a word or phrase formed by rearranging the letters of another word or phrase by using all the original letters exactly once. In other words, two strings are said to be anagrams of each other if they contain the same characters in the same quantity but possibly in a different order.

To solve this problem, we need to count how many characters appear an even number of times and at most one character can appear an odd number of times in a valid palindrome.

Using collections.Counter Class

The Counter class from the collections module in Python is used for counting how many times each character appears in a string. To build the longest palindrome using the characters from the string, we use all even-count characters and if available, one character with an odd count placed in the middle.

Example 1: Basic Approach

The following example shows how to count each character using the Counter class to determine the length of the longest subsequence that can be rearranged as a palindrome ?

from collections import Counter

def longest_anagram_subsequence_length(s):
    freq = Counter(s)
    length = 0
    odd_found = False

    for count in freq.values():
        if count % 2 == 0:
            length += count
        else:
            length += count - 1
            odd_found = True

    if odd_found:
        length += 1

    return length

# Sample input string
s = "abccccdd"
print("Length of longest anagram subsequence:", longest_anagram_subsequence_length(s))

The output of the above code is ?

Length of longest anagram subsequence: 7

Example 2: Optimized Approach

Below is another example where we calculate the length using a more concise approach ?

from collections import Counter

def longest_palindrome_length(s):
    count = Counter(s)
    result = 0
    
    for freq in count.values():
        result += (freq // 2) * 2
        if result % 2 == 0 and freq % 2 == 1:
            result += 1
            
    return result

# Sample input string
s = "aabbc"
print("Longest anagram subsequence length:", longest_palindrome_length(s))

The output of the above code is ?

Longest anagram subsequence length: 5

How It Works

The algorithm works by following these steps:

  • Count frequencies: Use Counter to count occurrences of each character
  • Add even counts: All characters with even counts can be fully used
  • Handle odd counts: For odd counts, use (count-1) characters and keep track if any odd count exists
  • Add center character: If any character has odd count, add 1 for the center position

Comparison

Approach Time Complexity Space Complexity Best For
Basic Approach O(n) O(k) Clear logic flow
Optimized Approach O(n) O(k) Concise implementation

where n is the string length and k is the number of unique characters

Conclusion

Both approaches use Counter to count character frequencies and build the longest possible palindrome. The key insight is that a palindrome can have at most one character with odd frequency (placed in the center).

Updated on: 2026-03-25T11:19:23+05:30

426 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements