Drill

ProblemsJava › warmup

Are these two an anagram

mediumwarmupHash mapsStringsSortingJava

A word game checks whether one phrase uses exactly the same letters as another.

isAnagram(text: string, other: string) → bool

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

boolean isAnagram(String text, String other) {
    
}

Worked examples

CallResult
isAnagram("Listen", "Silent")true
isAnagram("a b", "ba")true
isAnagram("hello", "world")false
isAnagram("abc", "ab")false

Hint

Strip and lowercase both, then compare the sorted characters, or count them.

Reference solution in Java
boolean isAnagram(String text, String other) {
    char[] a = text.toLowerCase().replaceAll("\\s+", "").toCharArray();
    char[] b = other.toLowerCase().replaceAll("\\s+", "").toCharArray();
    Arrays.sort(a);
    Arrays.sort(b);
    return Arrays.equals(a, b);
}

The same problem in another language

More warmup problems in Java