easyString ProblemsJava

Check Whether Two Strings Are Anagrams

Determine whether two strings are anagrams by comparing their character counts.

Quick Answer

Two strings are anagrams if they contain the same characters with the same counts. Keep one integer array of size 256, add one for each character of the first string and subtract one for each character of the second. If every count ends at zero, they are anagrams. This runs in O(n) time.

Problem Statement

Given two strings, determine whether they are anagrams of each other. Two strings are anagrams when one can be rearranged to form the other, meaning they contain exactly the same characters with the same frequencies.

Return true if the strings are anagrams and false otherwise. Treat the comparison as case-sensitive over the raw characters unless told otherwise.

Input: Two strings a and b.

Output: A boolean: true if the strings are anagrams, otherwise false.

Examples

Example 1
Input:  "listen", "silent"
Output: true

Both strings contain one each of l, i, s, t, e, n.

Example 2
Input:  "hello", "world"
Output: false

The letter counts differ, so no rearrangement can match.

Constraints

  • 0 <= a.length, b.length <= 10^5
  • Compare characters directly (no sorting is required)

Think Before You Code

Reveal the questions to ask yourself first
  • If two strings have different lengths, can they ever be anagrams?
  • How can you record how many times each character appears?
  • Instead of two separate counts, can one array track the difference?
  • Does the comparison need to ignore case or spaces for your version?

Hints

Open them one at a time — try after each before revealing the next.

Hint 1
If the two strings have different lengths, you can return false immediately.
Hint 2
Count characters. An int array indexed by the character value gives you an O(1) tally per character.
Hint 3
Add for every character of the first string and subtract for every character of the second. If all counts are zero at the end, they are anagrams.

Approach

Reveal the step-by-step approach

Compare the two strings by their character frequencies.

  1. If the lengths differ, return false — different lengths can never be anagrams.
  2. Create an int[256] count array (one slot per possible char value).
  3. Walk both strings together: count[a.charAt(i)]++ and count[b.charAt(i)]--.
  4. After the loop, scan the array. If any slot is non-zero, some character appeared a different number of times, so return false.
  5. If every slot is zero, the strings are anagrams — return true.

Adding for one string and subtracting for the other means matching characters cancel out to zero, leaving only genuine differences behind.

Dry Run

Walk through the example step by step

Checking "listen" against "silent":

index | a | b | count[a]++ | count[b]--
------+---+---+-----------+-----------
0     | l | s |  l -> +1   |  s -> -1
1     | i | i |  i -> +1   |  i -> 0
2     | s | l |  s -> 0    |  l -> 0
3     | t | e |  t -> +1   |  e -> -1
4     | e | n |  e -> 0    |  n -> -1
5     | n | t |  n -> 0    |  t -> 0
final : every slot is 0 -> true

Solution

Reveal the full Java solution
public class Anagram {
    public static boolean areAnagrams(String a, String b) {
        if (a.length() != b.length()) {
            return false;
        }
        int[] count = new int[256];
        for (int i = 0; i < a.length(); i++) {
            count[a.charAt(i)]++;
            count[b.charAt(i)]--;
        }
        for (int c : count) {
            if (c != 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(areAnagrams("listen", "silent")); // true
        System.out.println(areAnagrams("hello", "world"));   // false
    }
}

A single pass fills the count array: characters from a push counts up and the same positions of b push them down. Any character that appears the same number of times in both strings nets to zero. A leftover non-zero value means a mismatch, so the strings are not anagrams. The size-256 array covers all extended-ASCII characters; for Unicode you would use a HashMap<Character, Integer> instead.

Time: O(n) where n is the string lengthSpace: O(1) — the count array is a fixed 256 slots

Common Mistakes

  • Skipping the length check and reading past the end of the shorter string.
  • Sorting both strings first — correct but O(n log n) and slower than counting.
  • Assuming case does not matter without lowercasing both strings first.

Edge Cases to Test

  • Two empty strings are anagrams of each other (return true).
  • Strings of different length are never anagrams.
  • Identical strings like "abc" and "abc" are anagrams.

Interview Follow-Ups

  • How would you make the check case-insensitive and ignore spaces?
  • How would you handle full Unicode characters beyond ASCII?
  • How would you group a list of words into sets of mutual anagrams?

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Explore the Java Full Stack program →
Chat with us