Java string interview programs: anagram, first non-repeating character and frequency

Four string problems that come up in almost every Java coding round: check two anagrams, find the first non-repeating character, find the first repeating character, and count each character. They all come down to one skill: counting things.

Checking whether listen and silent are anagrams with an array of 26 counters, one per letter from a to z. Each letter of listen adds 1 to its counter and each letter of silent takes 1 away. The counters for e, i, l, n, s and t are highlighted yellow and all end at 0. A dark box says: all zero means anagram, O(n) time, O(1) space.
Fig. 1 — One array of 26 counters. Add for one word, subtract for the other, and check for zeros.

In Phase 1 you walked arrays of numbers. A String is really just an array of characters, so the same loops work. What’s new here is counting: how many times does each character appear?

There are three ways to count, and you’ll use all three in this article:

Tool Use it when
int[26] the input is only lowercase English letters a to z
HashMap<Character, Integer> any characters, order doesn’t matter
LinkedHashMap<Character, Integer> any characters, and you need the order they first appeared

8. Check if two strings are anagrams

Problem: two words are anagrams if they use exactly the same letters the same number of times. listen and silent are anagrams. hello and world are not.

Approach 1: a frequency array

Plan: keep 26 counters, one per letter. For each letter of the first word, add 1 to its counter. For each letter of the second word, take 1 away. If every counter ends at 0, the words are anagrams.

How do you find a letter’s counter? c - 'a'. Characters are numbers underneath, so 'a' - 'a' is 0, 'b' - 'a' is 1, and 'z' - 'a' is 25.

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;
}
isAnagram("listen", "silent")  → true
isAnagram("hello", "world")    → false

The length check at the top is a free early exit: different lengths can never be anagrams.

Cost: O(n) time. The array is always 26 ints, whatever the input size, so it’s O(1) space.

Approach 2: sort both and compare

Plan: if two words are anagrams, sorting their letters gives the same result. listen → eilnst, silent → eilnst.

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

Shorter and easier to remember, but slower: sorting is O(n log n).

Interview follow-ups:

  • What about capital letters and spaces, like “Dormitory” and “Dirty room”? Clean the input first: s.replaceAll("\\s", "").toLowerCase().
  • What about any Unicode character? int[26] breaks. Use a HashMap<Character, Integer> instead, like problem 11 below.

9. First non-repeating character

Problem: in "swiss", s appears three times, w once and i once. The first character that appears exactly once is 'w'.

Plan: two passes. First pass: count every character in a map. Second pass: walk the string again, in its original order, and return the first character whose count is 1.

static Character firstNonRepeating(String s) {
    Map<Character, Integer> count = new HashMap<>();
    for (char c : s.toCharArray()) {
        count.put(c, count.getOrDefault(c, 0) + 1);
    }
    for (char c : s.toCharArray()) {
        if (count.get(c) == 1) return c;
    }
    return null; // every character repeats
}
firstNonRepeating("swiss") → w
firstNonRepeating("aabb")  → null

What does getOrDefault do? count.get(c) returns null the first time you see a character, and null + 1 would crash. getOrDefault(c, 0) returns 0 instead when the key isn’t there. This one line is the heart of almost every counting problem in Java, so learn it by heart.

Why walk the string the second time, not the map? A HashMap doesn’t keep any order. If you looped over the map, you might find i before w.

The LinkedHashMap version

A LinkedHashMap remembers the order in which keys were first added. So you can loop over the map itself:

static Character firstNonRepeating(String s) {
    Map<Character, Integer> count = new LinkedHashMap<>();
    for (char c : s.toCharArray()) {
        count.put(c, count.getOrDefault(c, 0) + 1);
    }
    for (Map.Entry<Character, Integer> e : count.entrySet()) {
        if (e.getValue() == 1) return e.getKey();
    }
    return null;
}

Both are O(n) time. The second loop is shorter when the string is long but has few distinct characters.

10. First repeating character

Problem: in "hello", the first character we meet for the second time is 'l'.

Plan: you don’t need counts here, just “have I seen this before?”. That’s exactly what a HashSet answers. Walk the string. If the character is already in the set, return it. Otherwise, add it.

static Character firstRepeating(String s) {
    Set<Character> seen = new HashSet<>();
    for (char c : s.toCharArray()) {
        if (seen.contains(c)) return c;
        seen.add(c);
    }
    return null; // no repeats
}
firstRepeating("hello") → l
firstRepeating("java")  → a
firstRepeating("abc")   → null

A shorter trick: Set.add returns false when the element was already there. So the loop body can be one line:

if (!seen.add(c)) return c;

Watch the definition. For "abba", this code returns b, because the second b appears before the second a. Some interviewers mean “the first character in the string that appears more than once”, which is a. For that version, count first (like problem 9) and return the first character with count greater than 1. Ask which one they mean. Asking is a good sign, not a weak one.

Cost: O(n) time, O(k) space for k distinct characters.

11. Character frequency

Problem: print how many times each character appears in "programming".

p=1
r=2
o=1
g=2
a=1
m=2
i=1
n=1

This is the most important problem in this phase. Words, numbers, log lines, employees per department: the same few lines count all of them.

String s = "programming";
Map<Character, Integer> freq = new LinkedHashMap<>();
for (char c : s.toCharArray()) {
    freq.put(c, freq.getOrDefault(c, 0) + 1);
}
for (Map.Entry<Character, Integer> e : freq.entrySet()) {
    System.out.println(e.getKey() + "=" + e.getValue());
}

entrySet() gives you each key and value together as a Map.Entry. It’s the normal way to loop over a map when you need both.

Which map, which order?

The same counts come out in a different order depending on the map:

new HashMap<>()       // {p=1, a=1, r=2, g=2, i=1, m=2, n=1, o=1}   no promised order
new LinkedHashMap<>() // {p=1, r=2, o=1, g=2, a=1, m=2, i=1, n=1}   order of first appearance
new TreeMap<>()       // {a=1, g=2, i=1, m=2, n=1, o=1, p=1, r=2}   sorted by key

If the interviewer’s expected output is in “first appearance” order, a plain HashMap gives the right counts but the wrong order. Choosing LinkedHashMap on purpose, and saying why, is exactly what they want to see.

Two other ways to write the counting line

freq.merge(c, 1, Integer::sum);   // "put 1, or add 1 to what's there"

merge is shorter, and you’ll see it a lot in later phases. And for lowercase letters only, the int[26] array from problem 8 works too:

int[] counts = new int[26];
for (char c : s.toCharArray()) counts[c - 'a']++;
for (int i = 0; i < 26; i++) {
    if (counts[i] > 0) System.out.println((char) ('a' + i) + "=" + counts[i]);
}

That prints in alphabetical order, like the TreeMap.

What you practised

  • Counting with an int[26] array, a HashMap and a LinkedHashMap
  • getOrDefault and merge for “start at 0, then add 1”
  • HashSet for “have I seen this?”, and the add returns false trick
  • entrySet() to loop over keys and values together
  • Choosing a map for its order: none, first appearance, or sorted

Next: Phase 3, ArrayList and Set interview programs, where you remove duplicates, find common elements and sort lists.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.