🔥 Launch Offer: Interview Preparation Bundle @ ₹2,499 ₹9,999 • 75% OFF. Offer expires in 🔥 Launch Offer: Interview Preparation Bundle @ ₹2,499 ₹9,999 • 75% OFF. Offer expires in Interview Preparation Bundle @ ₹2,499 ₹9,999

00:00:00 Get Bundle
home / practice / first-non-repeating-character
medium Collection Framework

First non-repeating character

Given a string s, return the first character that appears exactly once. If none exists, return '_'. Prefer LinkedHashMap so insertion order is preserved while you count frequencies.

Example

Input:  "swiss"
Output: 'w'

Input:  "aabb"
Output: '_'

Starter code

import java.util.*;

public class FirstUnique {
    public static char firstUnique(String s) {
        // TODO
        return '_';
    }

    public static void main(String[] args) {
        System.out.println(firstUnique("swiss"));
        System.out.println(firstUnique("aabb"));
    }
}

Solution

import java.util.*;

public class FirstUnique {
    public static char firstUnique(String s) {
        Map<Character, Integer> freq = new LinkedHashMap<>();
        for (char c : s.toCharArray()) {
            freq.merge(c, 1, Integer::sum);
        }
        for (Map.Entry<Character, Integer> e : freq.entrySet()) {
            if (e.getValue() == 1) {
                return e.getKey();
            }
        }
        return '_';
    }

    public static void main(String[] args) {
        System.out.println(firstUnique("swiss"));
        System.out.println(firstUnique("aabb"));
    }
}