</>

Technology

Java Programs

Difficulty

Intermediate

Interview Question

Write a Java program to find the first non-repeating character in a string.

Answer

First Non-Repeating Character in a String

Method 1: LinkedHashMap (Preserves Insertion Order)

Java
import java.util.LinkedHashMap;
import java.util.Map;

public class FirstNonRepeatingChar {
    public static void main(String[] args) {
        String str = "aabbcdeeff";

        LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();

        // Build frequency map (insertion order preserved)
        for (char c : str.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }

        // Find first character with count = 1
        char result = ' ';
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 1) {
                result = entry.getKey();
                break;
            }
        }

        if (result != ' ')
            System.out.println("First non-repeating char: " + result);
        else
            System.out.println("No non-repeating character found");
    }
}

Output

CODE
First non-repeating char: c

Method 2: Two-Pass with int Array (O(n) — Fastest)

Java
public static char firstNonRepeating(String str) {
    int[] freq = new int[256];  // ASCII frequency array

    // Pass 1: count frequency of each char
    for (char c : str.toCharArray()) freq[c]++;

    // Pass 2: find first char with frequency 1
    for (char c : str.toCharArray()) {
        if (freq[c] == 1) return c;
    }
    return '\0';  // no non-repeating char found
}

System.out.println(firstNonRepeating("aabbcdeeff")); // c
System.out.println(firstNonRepeating("aabb"));        // \0 (none)
System.out.println(firstNonRepeating("Selenium"));    // S

Method 3: Java 8 Stream

Java
String str = "aabbcdeeff";

Optional<Character> first = str.chars()
    .mapToObj(c -> (char) c)
    .filter(c -> str.indexOf(c) == str.lastIndexOf(c))  // appears only once
    .findFirst();

first.ifPresent(c -> System.out.println("First non-repeating: " + c));
// → c

Test Multiple Strings

Java
String[] tests = { "aabbcdeeff", "aabb", "Selenium", "swiss", "abcdef" };

for (String s : tests) {
    char result = firstNonRepeating(s);
    System.out.println("\"" + s + "\" → " +
        (result == '\0' ? "None" : String.valueOf(result)));
}

Output

CODE
"aabbcdeeff" → c
"aabb"       → None
"Selenium"   → S
"swiss"      → w
"abcdef"     → a

LinkedHashMap vs HashMap — Why It Matters Here

CODE
HashMap:       {a=2, b=2, c=1, d=1, e=2, f=2}  → order NOT guaranteed
LinkedHashMap: {a=2, b=2, c=1, d=1, e=2, f=2}  → insertion order guaranteed
               → iterating gives c as first with count 1 ✓

Follow AutomateQA