Skip to content
The Chat Archive
claude-2.0· Anthropic Arena Human Preference 55K

Write a python function that helps me find the longest anagram in a given string

  1. User

    Write a python function that helps me find the longest anagram in a given string

  2. Assistant

    Here is a python function to find the longest anagram in a given string:

    def find_longest_anagram(text):
      n = len(text)
      longest = ''
      for i in range(n):
        for j in range(i+1,n+1):
          sub = text[i:j]
          if len(sub) > len(longest) and is_anagram(sub):
            longest = sub
      return longest
    
    def is_anagram(s1):
      s2 = ''.join(sorted(s1))
      return s1 == s2
    

    The key steps are:

    • Iterate through all substrings of the input text using two nested loops.
    • Check if each substring is an anagram by sorting the characters and comparing to original.
    • Keep track of the longest anagram seen so far.
    • Return the longest anagram.

    To check if a string is an anagram, we sort the characters and compare to the original. This handles duplicate characters properly.

    The overall time complexity is O(n^2 log n) due to the sorting in the is_anagram function.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.