Data Structures & AlgorithmsModerateGATE CS · DSA

How many characters must be deleted in total from two strings so that they become anagrams of each other? What is printed?

How many characters must be deleted in total from two strings so that they become anagrams of each other? What is printed?
from collections import Counter
a, b = "ddbabbeb", "cddbee"
ca, cb = Counter(a), Counter(b)
print(sum(((ca - cb) + (cb - ca)).values()))
  1. A. 6
  2. B. 4
  3. C. 2
  4. D. 14

Correct answer: A. 6

Each letter contributes |count in a − count in b| deletions; Counter subtraction drops non-positive counts, so both directions are needed: 4 + 2 = 6. Using only ca − cb gives 4, the length difference is 2 and 14 is the total length.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic