Check whether two strings are anagrams.

Check whether two strings are anagrams with a 26-count array in O(n), the sorting approach, a HashMap for Unicode, and how to ignore spaces and case.

0 0
Read Time:1 Minute, 40 Second

Two strings are anagrams if they contain the same characters the same number of times, in any order: “listen” and “silent”, “debit card” and “bad credit” (ignoring spaces).

Counting array (O(n), the answer to give)

static boolean isAnagram(String a, String b) {
    if (a.length() != b.length()) return false;
    int[] count = new int[26];
    for (int i = 0; i < a.length(); i++) {
        count[a.charAt(i) - 'a']++;
        count[b.charAt(i) - 'a']--;
    }
    for (int c : count) if (c != 0) return false;
    return true;
}

One pass increments for the first string and decrements for the second. If every count is back to zero, they are anagrams. Time O(n), space O(1) because the array size is fixed at 26. This assumes lowercase a to z; say that assumption out loud.

Sorting (simple, O(n log n))

static boolean isAnagramSort(String a, String b) {
    char[] x = a.toCharArray(), y = b.toCharArray();
    Arrays.sort(x);
    Arrays.sort(y);
    return Arrays.equals(x, y);
}

Any characters, ignoring case and spaces

static boolean isAnagramAny(String a, String b) {
    Map<Integer, Integer> m = new HashMap<>();
    a.toLowerCase().codePoints().filter(c -> c != ' ').forEach(c -> m.merge(c, 1, Integer::sum));
    b.toLowerCase().codePoints().filter(c -> c != ' ').forEach(c -> m.merge(c, -1, Integer::sum));
    return m.values().stream().allMatch(v -> v == 0);
}

Mistakes to avoid

  • Checking only that each character of one string appears in the other: “aab” and “abb” would pass.
  • Forgetting the length check, which is the cheapest early exit.
  • Not clarifying case, spaces and character set before coding.

Follow-up

Group a list of words into anagram groups: use the sorted word (or the 26-count signature) as a HashMap key.

This answer was written by Debugger’s Space as practice material. It is asked in most Indian IT services interviews (TCS, Infosys, Wipro, HCLTech, Tech Mahindra, LTIMindtree, Accenture, Cognizant, Capgemini, IBM). See each company’s hiring steps and practice questions on Debugger’s Space.

Previous post Find the second largest number in an array in one pass.
Next post Find the first non-repeating character in a string.
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Close
0
Would love your thoughts, please comment.x
()
x