Anagram
An anagram is word switch or word play. It is the result of rearranging the letters of a word or phrase to produce a new word or phrase, while using all the original letters only once.
In interviews, usually we are only bothered with words without spaces in them.
ToLet's determinebreak ifdown twothe three common approaches in very simple terms:
-
Sorting Both Strings
- How it works:
Rearrange (sort) the letters of both strings alphabetically. If the sorted versions are exactly the same, then the strings areanagrams, there are a few approaches:- anagrams.
- Time Cost:
SortingbothtakesstringsaboutshouldO(nproducelog n) time, where n is the number of characters. - Space Cost:
It typically uses extra space proportional to the depth of recursion (about O(log n)). - Simple Analogy:
Imagine you have two mixed-up decks of cards. If you sort them by suit and number, and they end up in the sameresultingorder,string.then- both
ThisdeckstakesoriginallyO(n.log(n))hadtimetheandsameO(log(n)) space.cards.
IfwePrime
mapMultiplication Method- How it works:
Assign eachcharacter toletter a unique prime numberand(likewea secret code). For each string, multiplyeachthemappedprimesnumbercorrespondingtogether,toanagramsitsshouldletters. Thanks to the unique nature of prime factors, two strings will have the samemultipleproduct(primeiffactoranddecomposition).only- if they have the exact same letters.
ThisTime Cost:
You only go through the string once, so it takes O(n)timetime.- Space Cost:
It uses constant extra space, O(1), since the mapping of letters to primes is fixed. - Simple Analogy:
Think of it like each letter is a unique ingredient with a special "number." Mix them all together (multiply), andO(1)ifspace.twoExamples:recipesGroup(strings)Anagramyield the same "flavor number," they contain exactly the same ingredients.
- How it works:
-
Frequency
countingCountingof- How
willithelpworks:
Counttohowdeterminemanyiftimestwoeach letter appears in each string using a hash (dictionary). Then, compare these counts. If they match for every letter, the strings are anagrams. - Time Cost:
This also takes O(n)timetime, as you just make one pass through each string. - Space Cost:
It uses constant extra space, O(1), because the number of letters (for example, 26 for the English alphabet) is fixed. - Simple Analogy:
Imagine you have two baskets of fruit. If you count the number of apples, oranges, etc., in both baskets andO(1)thespace.counts match exactly, then both baskets have the same mix of fruits.
characters - How
- How it works:
Each method has its tradeoffs between speed and space:
- Sorting is straightforward but slightly slower due to the sorting process.
- Prime multiplication is fast and space-efficient, but it can run into issues with very long strings because the multiplication might produce huge numbers.
- Frequency counting is both fast and efficient, and it's often the simplest and most reliable method.