0
0
KotlinProgramBeginner · 2 min read

Kotlin Program to Check Anagram with Example

You can check an anagram in Kotlin by comparing sorted versions of two strings using str1.toCharArray().sorted() == str2.toCharArray().sorted().
📋

Examples

Inputlisten, silent
OutputAnagram
Inputhello, world
OutputNot an Anagram
Inputaabbcc, abcabc
OutputAnagram
🧠

How to Think About It

To check if two words are anagrams, think about whether they have the same letters in the same amounts. If you sort the letters of both words and they match exactly, then they are anagrams.
📐

Algorithm

1
Get two input strings.
2
Convert both strings to character arrays.
3
Sort both character arrays.
4
Compare the sorted arrays.
5
If they are equal, return that they are anagrams; otherwise, return they are not.
💻

Code

kotlin
fun main() {
    val str1 = "listen"
    val str2 = "silent"
    if (str1.toCharArray().sorted() == str2.toCharArray().sorted()) {
        println("Anagram")
    } else {
        println("Not an Anagram")
    }
}
Output
Anagram
🔍

Dry Run

Let's trace the example with inputs 'listen' and 'silent' through the code.

1

Input strings

str1 = 'listen', str2 = 'silent'

2

Convert to char arrays and sort

str1.toCharArray().sorted() = [e, i, l, n, s, t], str2.toCharArray().sorted() = [e, i, l, n, s, t]

3

Compare sorted arrays

Both arrays are equal

4

Print result

Output: 'Anagram'

StepSorted str1Sorted str2Are 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

Using frequency count with maps
kotlin
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")
    }
}
This method counts how many times each letter appears and compares counts; it can be faster for very long strings.
Using character array and manual count
kotlin
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")
}
This approach uses an array to count characters and is efficient but assumes ASCII characters.

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.

ApproachTimeSpaceBest For
Sorting and comparingO(n log n)O(n)Simple and small to medium strings
Frequency count with mapsO(n)O(n)Strings with many characters, Unicode support
Frequency count with arrayO(n)O(1)ASCII strings, very fast and memory efficient
💡
Always normalize strings by removing spaces and converting to lowercase before checking anagrams.
⚠️
Forgetting to handle case differences or spaces can cause false negatives in anagram checks.