Java 8: Find the first non-repeating character in a string. Compare all approaches.
Problem
"swiss" → 'w', "aabb" → none. One of the most frequently asked Java string questions.
Approach 1: indexOf equals lastIndexOf (feasible, O(n²))
A character is unique if its first and last positions are the same. One line, but each check scans the string.
class FirstUniqueBrute {
static Character find(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (s.indexOf(c) == s.lastIndexOf(c)) return c;
}
return null;
}
}Approach 2: LinkedHashMap of counts (O(n), any Unicode character)
Count in insertion order, then return the first entry with count one.
import java.util.LinkedHashMap;
import java.util.Map;
class FirstUniqueMap {
static Character find(String s) {
Map<Character, Integer> counts = new LinkedHashMap<>();
for (char c : s.toCharArray()) counts.merge(c, 1, Integer::sum);
for (Map.Entry<Character, Integer> e : counts.entrySet()) {
if (e.getValue() == 1) return e.getKey();
}
return null;
}
}Approach 3: int[] counts, two passes (O(n), O(1) space: optimal for ASCII/Latin-1)
An array indexed by character code replaces hashing and boxing. The second pass walks the string, not the map, so order is free.
class FirstUniqueArray {
static Character find(String s) {
int[] counts = new int[256];
for (int i = 0; i < s.length(); i++) counts[s.charAt(i) & 0xFF]++;
for (int i = 0; i < s.length(); i++) {
if (counts[s.charAt(i) & 0xFF] == 1) return s.charAt(i);
}
return null;
}
}For full Unicode use int[65536] or the map version.
Approach 4: Java 8 Streams (O(n), declarative)
Group characters into a LinkedHashMap with counts, then find the first entry with count one.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
class FirstUniqueStreams {
static Character find(String s) {
return s.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
}
}Approach 5: One pass with first-index tracking (O(n + alphabet), good for very long strings or streams)
Store the first index of each character, or a marker once it repeats; the answer is the smallest stored index. You never re-read the input, which matters when it arrives as a stream you cannot rewind.
import java.util.Arrays;
class FirstUniqueOnePass {
private static final int REPEATED = -2, UNSEEN = -1;
static Character find(CharSequence input) {
int[] first = new int[256];
Arrays.fill(first, UNSEEN);
for (int i = 0; i < input.length(); i++) {
int c = input.charAt(i) & 0xFF;
first[c] = first[c] == UNSEEN ? i : REPEATED;
}
int best = Integer.MAX_VALUE;
for (int idx : first) if (idx >= 0 && idx < best) best = idx;
return best == Integer.MAX_VALUE ? null : input.charAt(best);
}
}Run all approaches
class FirstUniqueDemo {
public static void main(String[] args) {
for (String s : new String[] {"swiss", "programming", "aabb"}) {
System.out.println(s + " -> " + FirstUniqueBrute.find(s) + " " + FirstUniqueMap.find(s) + " "
+ FirstUniqueArray.find(s) + " " + FirstUniqueStreams.find(s) + " " + FirstUniqueOnePass.find(s));
}
// swiss -> w w w w w ; programming -> p p p p p ; aabb -> null null null null null
}
}Feasible → optimal
indexOf == lastIndexOf: O(n²), shortest to write.LinkedHashMapor StreamsgroupingBy: O(n), handles any character, boxing overhead.int[]counts with two passes: O(n), O(1) space, fastest for a known alphabet.- One pass with first-index array: O(n + alphabet), single read of the input.
Follow-up questions interviewers ask
Try answering each one before you open it.
How would you find the first non-repeating character in a live stream of characters, at any moment?
Keep counts in an array and a queue (or a LinkedHashSet) of characters seen exactly once. On each new character, increment its count; if it becomes 1 add it to the queue, if it becomes 2 remove it. The answer at any time is the head of the queue: O(1) per character.
What changes for emoji and other characters outside the BMP?
charAt and chars() work on UTF-16 code units, so an emoji is two surrogate chars and would be counted as two characters. Use s.codePoints() and a Map<Integer, Long> keyed by code point, or BreakIterator for user-perceived characters such as flags.