Counting with arrays
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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})); }}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 indices0..9, ignoring the hyphen'-'.- For temperatures in
[-5 .. 5], subtractingminVal(-5) shifts-5to index0and+5to index10.
- Lowercase
'a'..'z':new int[26], indexc - 'a'. - Uppercase
'A'..'Z':new int[26], indexc - 'A'. - Digits
'0'..'9':new int[10], indexc - '0'. - Integers in
[min..max]:new int[max - min + 1], indexx - min.
Subtracting 'a' from any lowercase letter c shifts its code into the exact array index range 0 .. 25:
'a' - 'a'is0'b' - 'a'is1'z' - 'a'is25Withint[] freq = new int[26], incrementingfreq[c - 'a']++records an occurrence ofcin a single array-index operation with zero object allocations. The same offset trick works for:- Digits
'0'..'9':int[] digits = new int[10];indexed byc - '0'. - ASCII characters (
0..127):int[] ascii = new int[128];indexed directly byc. - Bounded integers in
[minVal .. maxVal](for example, test scores0..100or temperatures-50..50):int[] counts = new int[maxVal - minVal + 1];indexed byval - minVal.
Predict the output
Read the count array
Read each snippet and pick the answer.
Round 1 of 2
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)
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")); }}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)
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")); }}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)
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")); }}listen / silent : true triangle / integral : true apple / pale : false rat / car : false
What this code does
- Every character in
sadds+1to its bucket and every character intsubtracts-1from its bucket. - If
sandthave the exact same character counts, every bucket cancels back to0. - 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)
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")); }}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)
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")); }}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 index2appears once (and'c'at index8also appears once). - Because Pass 2 scans the string indices
0 .. s.length() - 1rather than alphabetical buckets0 .. 25, it returns index2('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:
- Valid Anagram: Two strings
sandtare anagrams if they contain the exact same characters with the exact same frequencies. Brute force sorts both strings in O(n log n) time. Withint[] counts = new int[26], we first checks.length() == t.length(), then in one loop incrementcounts[s.charAt(i) - 'a']++and decrementcounts[t.charAt(i) - 'a']--. If all 26 entries end at0,sandtare anagrams in O(n) time and O(1) space. - First Unique Character in a String: Given lowercase string
s, return the index of the first character that appears only once, or-1if none exists. Brute force checks every other index for each character in O(n²) time. Withint[26], Pass 1 counts the frequency of every character ins, and Pass 2 scansi = 0 .. s.length() - 1(over the string, not the 26-bucket array!) and returns the firstiwherefreq[s.charAt(i) - 'a'] == 1. - For Valid Anagram: reject if
s.length() != t.length(), add+1fors.charAt(i)and-1fort.charAt(i), then check all 26 counts are0. - For First Unique Character: Pass 1 fills
freq[s.charAt(i) - 'a']++; Pass 2 loopsi = 0 .. s.length() - 1and returns the firstiwithfreq[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.
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)); }}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 in0..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⁹, arbitraryStringwords, or full Unicode text including emojis), where allocatingnew int[1_000_000_000]would waste gigabytes of RAM or throwOutOfMemoryError.
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