Q5: How do you find the first non-repeating character in a String?

Perform two passes over the string. Pass 1: Build a character frequency map (int[256] or LinkedHashMap). Pass 2: Iterate through the string from left to right; return the index of the first character whose frequency count equals 1.

First Unique Character Solution
public class FirstUniqueChar {
    public static int firstUniqChar(String s) {
        int[] freq = new int[256];
        for (int i = 0; i < s.length(); i++) {
            freq[s.charAt(i)]++;
        }
        for (int i = 0; i < s.length(); i++) {
            if (freq[s.charAt(i)] == 1) return i;
        }
        return -1;
    }
}
💡 Finds character frequencies in the first loop and locates the first unique element index in the second.
Key Takeaways
  • Pass 1 counts character frequencies.
  • Pass 2 preserves input ordering to identify the first unique character index.
Knowledge Check

Why does a second iteration over the string s (rather than iterating over the frequency array) guarantee finding the FIRST non-repeating character?