Command Palette

Search for a command to run...

Lesson 3.3 · Strings

Counting Letters with an Array of 26

A fixed-size count array is faster and simpler than a HashMap when the alphabet is small and known.

10 min

Think of it like this

Instead of a notebook where you write down each new letter you meet (a HashMap), you have a row of 26 jars labelled a to z. Dropping a pebble into jar c - 'a' is instant.

1.The count array

For lowercase English letters, int[] count = new int[26] and count[c - 'a']++ counts every letter in O(n) time and O(1) space (26 is a constant). Two strings are anagrams if their count arrays are equal.

For any ASCII character use new int[128] and index with the character directly.

Count.java
import java.util.Arrays;

public class Main {
    static int[] counts(String s) {
        int[] c = new int[26];
        for (char ch : s.toCharArray()) c[ch - 'a']++;
        return c;
    }
    public static void main(String[] args) {
        System.out.println(Arrays.equals(counts("listen"), counts("silent")));
        System.out.println(Arrays.equals(counts("rat"), counts("car")));
    }
}

Output

true
false

Remember

  • Small known alphabet → int[26] or int[128].
  • Equal count arrays ⇔ anagrams.
  • Count arrays are O(1) space because their size doesn't grow with n.

Common mistakes

  • Using int[26] when input has uppercase letters, digits or spaces (index out of bounds).