Kotlin Program to Check Anagram with Example
str1.toCharArray().sorted() == str2.toCharArray().sorted().Examples
How to Think About It
Algorithm
Code
fun main() {
val str1 = "listen"
val str2 = "silent"
if (str1.toCharArray().sorted() == str2.toCharArray().sorted()) {
println("Anagram")
} else {
println("Not an Anagram")
}
}Dry Run
Let's trace the example with inputs 'listen' and 'silent' through the code.
Input strings
str1 = 'listen', str2 = 'silent'
Convert to char arrays and sort
str1.toCharArray().sorted() = [e, i, l, n, s, t], str2.toCharArray().sorted() = [e, i, l, n, s, t]
Compare sorted arrays
Both arrays are equal
Print result
Output: 'Anagram'
| Step | Sorted str1 | Sorted str2 | Are Equal? |
|---|---|---|---|
| 2 | [e, i, l, n, s, t] | [e, i, l, n, s, t] | Yes |
Why This Works
Step 1: Sorting letters
Sorting the characters of both strings puts letters in order, making it easy to compare.
Step 2: Comparing sorted arrays
If the sorted arrays match exactly, it means both strings have the same letters in the same quantity.
Step 3: Result decision
Based on the comparison, the program prints 'Anagram' or 'Not an Anagram'.
Alternative Approaches
fun main() {
val str1 = "listen"
val str2 = "silent"
val freq1 = str1.groupingBy { it }.eachCount()
val freq2 = str2.groupingBy { it }.eachCount()
if (freq1 == freq2) {
println("Anagram")
} else {
println("Not an Anagram")
}
}fun main() {
val str1 = "listen"
val str2 = "silent"
if (str1.length != str2.length) {
println("Not an Anagram")
return
}
val count = IntArray(256)
for (c in str1) count[c.code]++
for (c in str2) count[c.code]--
if (count.all { it == 0 }) println("Anagram") else println("Not an Anagram")
}Complexity: O(n log n) time, O(n) space
Time Complexity
Sorting both strings takes O(n log n) time, where n is the length of the strings.
Space Complexity
Sorting creates new arrays, so extra space proportional to the string length is used.
Which Approach is Fastest?
Counting characters with arrays or maps can be O(n) and faster for large inputs, but sorting is simpler and good for small to medium strings.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sorting and comparing | O(n log n) | O(n) | Simple and small to medium strings |
| Frequency count with maps | O(n) | O(n) | Strings with many characters, Unicode support |
| Frequency count with array | O(n) | O(1) | ASCII strings, very fast and memory efficient |