Return the first character that appears exactly once (e.g. "swiss" -> "w").
Two passes over an ordered frequency map: first count every character, then return the first key whose count is 1. Using an insertion-ordered map keeps the second pass in original order. O(n) time.
public static Character firstUnique(String s) {
Map<Character,Integer> m = new LinkedHashMap<>();
for (char c : s.toCharArray()) m.merge(c, 1, Integer::sum);
for (var e : m.entrySet()) if (e.getValue() == 1) return e.getKey();
return null;
}function firstUnique(s) {
const m = new Map();
for (const c of s) m.set(c, (m.get(c) || 0) + 1);
for (const [c, count] of m) if (count === 1) return c;
return null;
}from collections import Counter
def first_unique(s):
counts = Counter(s)
for c in s:
if counts[c] == 1:
return c
return NoneThe "count then scan in order" pattern is reused for finding the first unique record in de-duplication and log triage.
A candidate returns a character as soon as its count hits 1 in a single pass. Why is that wrong?