← Back to libraryQuestion 57 of 273
⌨️Java CodingIntermediate

Find the First Non-Repeated Character

📌 Definition:

Return the first character that appears exactly once (e.g. "swiss" -> "w").

📖 Detailed Explanation:

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.

💻 Solutions:
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 None
🔑 Key Points:
  • Two passes: count, then find first with count == 1
  • Insertion-ordered map for the second pass
  • Decide the "none found" return value
  • Single-pass early return is a trap
🌍 Real-World Example:

The "count then scan in order" pattern is reused for finding the first unique record in de-duplication and log triage.

🎯 Scenario-Based Interview Question:

A candidate returns a character as soon as its count hits 1 in a single pass. Why is that wrong?