Junior — Middle
How to determine if two strings are anagrams of each other?
sobes.tech AI
Answer from AI
Two strings are anagrams if they contain the same characters in the same quantity, but in a different order.
A simple way to check for an anagram:
- Ensure the strings are of equal length.
- Sort the characters of both strings.
- Compare the sorted strings — if they are identical, the strings are anagrams.
Example in Kotlin:
fun areAnagrams(s1: String, s2: String): Boolean {
if (s1.length != s2.length) return false
return s1.toCharArray().sorted() == s2.toCharArray().sorted()
}