Skip to lesson

Counting with arrays

A HashMap<Character, Integer> can count anything, but boxing every char into a Character object and computing hashes adds heavy constant-factor overhead. Whenever keys come from a small fixed range like 'a'..'z' or '0'..'9', a plain int[] array is faster, simpler, and uses O(1) memory.

int[26] for lowercase letters and counting small ranges

A frequency array stores how many times each value appears, using the value as the index, for example counts[ch - 'a']++ for letters.

In Java, char is an unsigned 16-bit integer (UTF-16 code unit) under the hood. The 26 lowercase English letters 'a' through 'z' sit in a contiguous block of character codes from 97 ('a') to 122 ('z').

Example 1 · Counting digits and negative-to-positive integer ranges with an offset

OffsetRangeCountDemo.javaJava
import java.util.Arrays;
public class OffsetRangeCountDemo {    static int[] countDigits(String pin) {        int[] digits = new int[10];        for (int i = 0; i < pin.length(); i++) {            char c = pin.charAt(i);            if (c >= '0' && c <= '9') {                digits[c - '0']++;            }        }        return digits;    }
    // Counts temperatures in the range [-5 .. +5] using an offset of +5    static int mostFrequentTemp(int[] temps) {        int minVal = -5, maxVal = 5;        int[] freq = new int[maxVal - minVal + 1]; // 11 buckets for -5..5        int bestTemp = temps[0];        int bestCount = 0;        for (int t : temps) {            int count = ++freq[t - minVal];            if (count > bestCount) {                bestCount = count;                bestTemp = t;            }        }        return bestTemp;    }
    public static void main(String[] args) {        System.out.println("Digit counts of '90210-99' : " + Arrays.toString(countDigits("90210-99")));        System.out.println("Most frequent temp         : " + mostFrequentTemp(new int[]{-3, 2, -3, 0, -3, 2}));    }}
Output
Digit counts of '90210-99' : [2, 1, 1, 0, 0, 0, 0, 0, 0, 3]
Most frequent temp         : -3

What this code does

  • c - '0' maps '0'..'9' to indices 0..9, ignoring the hyphen '-'.
  • For temperatures in [-5 .. 5], subtracting minVal (-5) shifts -5 to index 0 and +5 to index 10.
  • Lowercase 'a'..'z': new int[26], index c - 'a'.
  • Uppercase 'A'..'Z': new int[26], index c - 'A'.
  • Digits '0'..'9': new int[10], index c - '0'.
  • Integers in [min..max]: new int[max - min + 1], index x - min.

Subtracting 'a' from any lowercase letter c shifts its code into the exact array index range 0 .. 25:

  • 'a' - 'a' is 0
  • 'b' - 'a' is 1
  • 'z' - 'a' is 25 With int[] freq = new int[26], incrementing freq[c - 'a']++ records an occurrence of c in a single array-index operation with zero object allocations. The same offset trick works for:
  • Digits '0'..'9': int[] digits = new int[10]; indexed by c - '0'.
  • ASCII characters (0..127): int[] ascii = new int[128]; indexed directly by c.
  • Bounded integers in [minVal .. maxVal] (for example, test scores 0..100 or temperatures -50..50): int[] counts = new int[maxVal - minVal + 1]; indexed by val - minVal.

Predict the output

Read the count array

Read each snippet and pick the answer.

Round 1 of 2

int[] counts = new int[26];
for (char c : "banana".toCharArray()) {
counts[c - 'a']++;
}
System.out.println(counts['a' - 'a'] + " " + counts['n' - 'a']);

Valid Anagram and First Unique Character

Valid Anagram and First Unique Character both start with a slow brute force and become O(n) with a 26-slot count array. The code below solves both.

Example 2 · Brute force: match each letter by scanning the other word (O(n²) time, O(n) space)

AnagramBruteDemo.javaJava
public class AnagramBruteDemo {    static boolean isAnagram(String s, String t) {        if (s.length() != t.length()) {            return false;        }        boolean[] used = new boolean[t.length()];        for (int i = 0; i < s.length(); i++) {            boolean found = false;            for (int j = 0; j < t.length(); j++) {                if (!used[j] && t.charAt(j) == s.charAt(i)) {                    used[j] = true;                    found = true;                    break;                }            }            if (!found) {                return false;            }        }        return true;    }
    public static void main(String[] args) {        System.out.println("listen / silent : " + isAnagram("listen", "silent"));        System.out.println("triangle / integral : " + isAnagram("triangle", "integral"));        System.out.println("apple / pale    : " + isAnagram("apple", "pale"));        System.out.println("rat / car       : " + isAnagram("rat", "car"));    }}
Output
listen / silent : true
triangle / integral : true
apple / pale    : false
rat / car       : false

What this code does

  • Each letter of s looks for an unused matching letter in t and marks it as used.
  • Scanning t for every letter of s is n × n steps, so it is O(n²) time with an extra boolean array.

Example 3 · Better: sort both words and compare (O(n log n) time, O(n) space)

AnagramSortDemo.javaJava
import java.util.Arrays;
public class AnagramSortDemo {    static boolean isAnagram(String s, String t) {        if (s.length() != t.length()) {            return false;        }        char[] a = s.toCharArray();        char[] b = t.toCharArray();        Arrays.sort(a);        Arrays.sort(b);        return Arrays.equals(a, b);    }
    public static void main(String[] args) {        System.out.println("listen / silent : " + isAnagram("listen", "silent"));        System.out.println("triangle / integral : " + isAnagram("triangle", "integral"));        System.out.println("apple / pale    : " + isAnagram("apple", "pale"));        System.out.println("rat / car       : " + isAnagram("rat", "car"));    }}
Output
listen / silent : true
triangle / integral : true
apple / pale    : false
rat / car       : false

What this code does

  • Two words are anagrams exactly when their sorted letters are equal, so one sort per word replaces the nested search.
  • Sorting costs O(n log n), faster than O(n²), and the two char[] copies use O(n) extra space.

Example 4 · Optimal: count letters with one int[26] array (O(n) time, O(1) space)

ValidAnagramDemo.javaJava
public class ValidAnagramDemo {    static boolean isAnagram(String s, String t) {        if (s.length() != t.length()) {            return false;        }        int[] counts = new int[26];        for (int i = 0; i < s.length(); i++) {            counts[s.charAt(i) - 'a']++;            counts[t.charAt(i) - 'a']--;        }        for (int c : counts) {            if (c != 0) {                return false;            }        }        return true;    }
    public static void main(String[] args) {        System.out.println("listen / silent : " + isAnagram("listen", "silent"));        System.out.println("triangle / integral : " + isAnagram("triangle", "integral"));        System.out.println("apple / pale    : " + isAnagram("apple", "pale"));        System.out.println("rat / car       : " + isAnagram("rat", "car"));    }}
Output
listen / silent : true
triangle / integral : true
apple / pale    : false
rat / car       : false

What this code does

  • Every character in s adds +1 to its bucket and every character in t subtracts -1 from its bucket.
  • If s and t have the exact same character counts, every bucket cancels back to 0.
  • It is faster than sorting because counting touches each letter once and never has to order them.

Example 5 · Brute force: compare each letter with every other letter (O(n²) time, O(1) space)

FirstUniqueBruteDemo.javaJava
public class FirstUniqueBruteDemo {    static int firstUniqChar(String s) {        for (int i = 0; i < s.length(); i++) {            boolean repeated = false;            for (int j = 0; j < s.length(); j++) {                if (i != j && s.charAt(i) == s.charAt(j)) {                    repeated = true;                    break;                }            }            if (!repeated) {                return i;            }        }        return -1;    }
    public static void main(String[] args) {        System.out.println("leetcode     -> index " + firstUniqChar("leetcode"));        System.out.println("loveleetcode -> index " + firstUniqChar("loveleetcode"));        System.out.println("aabb         -> index " + firstUniqChar("aabb"));    }}
Output
leetcode     -> index 0
loveleetcode -> index 2
aabb         -> index -1

What this code does

  • For each position, an inner loop checks whether the same letter appears anywhere else.
  • That is n checks of n letters, so O(n²) time. It gives the right answers but gets slow on long strings.

Example 6 · Optimal: count first, then scan with an int[26] table (O(n) time, O(1) space)

FirstUniqueCharDemo.javaJava
public class FirstUniqueCharDemo {    static int firstUniqChar(String s) {        int[] freq = new int[26];        // Pass 1: count occurrences of each letter        for (int i = 0; i < s.length(); i++) {            freq[s.charAt(i) - 'a']++;        }        // Pass 2: scan string left-to-right for the first character with count == 1        for (int i = 0; i < s.length(); i++) {            if (freq[s.charAt(i) - 'a'] == 1) {                return i;            }        }        return -1;    }
    public static void main(String[] args) {        System.out.println("leetcode     -> index " + firstUniqChar("leetcode"));        System.out.println("loveleetcode -> index " + firstUniqChar("loveleetcode"));        System.out.println("aabb         -> index " + firstUniqChar("aabb"));    }}
Output
leetcode     -> index 0
loveleetcode -> index 2
aabb         -> index -1

What this code does

  • In "loveleetcode", 'l' appears twice and 'o' appears twice, while 'v' at index 2 appears once (and 'c' at index 8 also appears once).
  • Because Pass 2 scans the string indices 0 .. s.length() - 1 rather than alphabetical buckets 0 .. 25, it returns index 2 ('v') rather than 'c'.
  • It is faster because the first pass counts every letter once, so the second pass answers 'is this letter unique?' with one array lookup instead of an inner loop.

Two classic interview problems show int[26] at its best:

  1. Valid Anagram: Two strings s and t are anagrams if they contain the exact same characters with the exact same frequencies. Brute force sorts both strings in O(n log n) time. With int[] counts = new int[26], we first check s.length() == t.length(), then in one loop increment counts[s.charAt(i) - 'a']++ and decrement counts[t.charAt(i) - 'a']--. If all 26 entries end at 0, s and t are anagrams in O(n) time and O(1) space.
  2. First Unique Character in a String: Given lowercase string s, return the index of the first character that appears only once, or -1 if none exists. Brute force checks every other index for each character in O(n²) time. With int[26], Pass 1 counts the frequency of every character in s, and Pass 2 scans i = 0 .. s.length() - 1 (over the string, not the 26-bucket array!) and returns the first i where freq[s.charAt(i) - 'a'] == 1.
  3. For Valid Anagram: reject if s.length() != t.length(), add +1 for s.charAt(i) and -1 for t.charAt(i), then check all 26 counts are 0.
  4. For First Unique Character: Pass 1 fills freq[s.charAt(i) - 'a']++; Pass 2 loops i = 0 .. s.length() - 1 and returns the first i with freq[s.charAt(i) - 'a'] == 1.

Choosing between an array and a HashMap for counting

Use an int[] count array when keys fall in a small known range, and a HashMap when they do not. The code below counts letters with an array and large IDs with a map.

ArrayOrMap.javaJava
import java.util.HashMap;import java.util.Map;
public class ArrayOrMap {    public static void main(String[] args) {        int[] letters = new int[26];                  // keys 'a'..'z': small, known range        for (char c : "banana".toCharArray()) letters[c - 'a']++;        System.out.println("a -> " + letters['a' - 'a']);        Map<Integer, Integer> freq = new HashMap<>(); // keys up to 10^9: use a map        for (int id : new int[] {1_000_000_007, 42, 1_000_000_007}) {            freq.put(id, freq.getOrDefault(id, 0) + 1);        }        System.out.println("1000000007 -> " + freq.get(1_000_000_007));    }}
Output
a -> 3
1000000007 -> 2

Use an int[] frequency array when the keys fall in a small, known range, and a HashMap when they do not:

  • Use an int[] array when the key range R = max - min + 1 is known and small (such as 26 letters, 128 ASCII chars, or integers in 0..10,000). Lookup and update are a single memory access with no boxing.
  • Use a HashMap<K, Integer> when keys come from a huge or unbounded domain (such as arbitrary 32-bit integers up to 10⁹, arbitrary String words, or full Unicode text including emojis), where allocating new int[1_000_000_000] would waste gigabytes of RAM or throw OutOfMemoryError.
In Pass 2 of First Unique Character, loop over the string indices i = 0 .. s.length() - 1, NOT over 0 .. 25. Looping 0 .. 25 finds the alphabetically first unique letter (e.g., 'a'), not the first unique letter in string order!

Next step

Check your understanding

10 quick questions