Ruby Program to Check Anagram with Examples and Explanation
str1.chars.sort == str2.chars.sort.Examples
How to Think About It
Algorithm
Code
def anagram?(str1, str2) str1.chars.sort == str2.chars.sort end puts anagram?("listen", "silent") # true puts anagram?("hello", "world") # false puts anagram?("aabbcc", "abcabc") # true
Dry Run
Let's trace the example anagram?("listen", "silent") through the code
Input strings
str1 = "listen", str2 = "silent"
Convert to character arrays
str1.chars = ["l", "i", "s", "t", "e", "n"], str2.chars = ["s", "i", "l", "e", "n", "t"]
Sort character arrays
str1.chars.sort = ["e", "i", "l", "n", "s", "t"], str2.chars.sort = ["e", "i", "l", "n", "s", "t"]
Compare sorted arrays
Both sorted arrays are equal
Return result
true
| Iteration | str1.chars.sort | str2.chars.sort | Equal? |
|---|---|---|---|
| 1 | ["e", "i", "l", "n", "s", "t"] | ["e", "i", "l", "n", "s", "t"] | true |
Why This Works
Step 1: Convert strings to arrays
Using chars splits the string into individual letters so we can compare them easily.
Step 2: Sort the arrays
Sorting arranges letters in order, so anagrams will have identical sorted arrays.
Step 3: Compare sorted arrays
If both sorted arrays match exactly, the strings are anagrams; otherwise, they are not.
Alternative Approaches
def anagram?(str1, str2) str1.chars.tally == str2.chars.tally end puts anagram?("listen", "silent") # true puts anagram?("hello", "world") # false
def anagram?(str1, str2) clean1 = str1.downcase.gsub(/\s+/, '') clean2 = str2.downcase.gsub(/\s+/, '') clean1.chars.sort == clean2.chars.sort end puts anagram?("Listen", "Silent") # true puts anagram?("Hello", "World") # false
Complexity: O(n log n) time, O(n) space
Time Complexity
Sorting the characters takes O(n log n) time, where n is the length of the string. This dominates the runtime.
Space Complexity
Extra space is needed to store the character arrays and their sorted versions, which is O(n).
Which Approach is Fastest?
Counting characters with tally can be faster (O(n)) than sorting, but sorting is simpler and more readable for beginners.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sorting characters | O(n log n) | O(n) | Simple and readable code |
| Counting characters (tally) | O(n) | O(n) | Large strings with performance needs |
| Sorting with cleaning (ignore case/space) | O(n log n) | O(n) | Checking phrases ignoring spaces and case |
chars.sort to quickly check anagrams by comparing sorted letters.