# Program to find length of longest anagram subsequence in Python

Suppose we have two lowercase strings S and T, we have to find the length of the longest anagram subsequence.

So, if the input is like S = "helloworld", T = "hellorld", then the output will be 8

• To solve this, we will follow these steps −

• c := a new map, d := a new map

• for i in range 0 to size of a, do

• if a[i] in c, then

• c[a[i]] := c[a[i]] + 1

• otherwise,

• c[a[i]] := 1

• for i in range 0 to size of b, do

• if b[i] in d, then

• d[b[i]] := d[b[i]] + 1

• otherwise,

• d[b[i]] := 1

• res := 0

• for each ch in c, do

• if d[ch] > 0, then

• res := res + minimum of c[ch] and d[ch]

• return res

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, a, b):
c, d = {}, {}
for i in range(len(a)):
if a[i] in c:
c[a[i]] += 1
else:
c[a[i]] = 1
for i in range(len(b)):
if b[i] in d:
d[b[i]] += 1
else:
d[b[i]] = 1
res = 0
for ch in c:
if d.get(ch, 0) > 0:
res += min(c[ch], d[ch])
return res
ob = Solution()
S = "helloworld"
T = "hellorld"
print(ob.solve(S, T))

## Input

S = "helloworld", T = "hellorld"

## Output

1