This problem may come up during an interview, and it’s a bit of fun. How do we determine if two strings are anagrams?
If you’re practicing for an interview, write your solution in a text editor rather than an IDE. For syntax coloring, Visual Studio Code without IntelliSense works well with support for many languages. I’ve provided my solution in C# (csharp) and Objective-C (ObjC) at the bottom. A Java solution would appear similar to C# and I’ve noted differences.
By definition, an anagram is a word or phrase formed from another word or phrase by rearranging the letters. Spaces and punctuation don’t count, just the letters ignoring case. Here are a few samples:
- “Tom Marvolo Riddle” <–> “I am Lord Voldemort!”
- “Dave Barry” <–> “Ray Adverb”
- “debit card” <–> “bad credit”
- “astronomer” <–> “Moon starer”
- “School master” <–> “the classroom”
Since we must use all of the letters we can conclude that ignoring spaces and punctuation, the two strings must be the same length. Also, the same phrase is not an anagram of itself.
Notice that if we sort the letters of a phrase and its anagram we get identical strings.