Anagram Check
Problem
Two lowercase words are given on two lines. Print true if they are anagrams (the same letters in a different order), else false.
Constraints
- 1 <= length <= 10^5, letters a-z
Examples
Input
listen silent
Output
true
Solutions
Anagrams have the same count of every letter. One table of counters is enough: add for the first word and subtract for the second one.
/*
* Problem : Check for an anagram.
* Input : Two lowercase words.
* Output : true or false.
* Approach: Count the letters.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static boolean solve(String a, String b) {
// Step 1: Words with different lengths can not be anagrams.
if (a.length() != b.length()) {
return false;
}
// Step 2: A table of 26 counters, one for each letter.
int[] counts = new int[26];
// Step 3: Add 1 for each letter of a and subtract 1 for each letter of b.
for (int i = 0; i < a.length(); i++) {
counts[a.charAt(i) - 'a']++;
counts[b.charAt(i) - 'a']--;
}
// Step 4: For anagrams all counters return to 0.
for (int count : counts) {
if (count != 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next();
String b = scanner.next();
System.out.println(solve(a, b));
}
}
Hints (1)
- What must be true about the lengths?