0
0
JavaProgramBeginner · 2 min read

Java Program to Find First Non Repeating Character

Use a Java program that counts character frequencies with a LinkedHashMap and then iterates to find the first character with count 1, like for (char c : input.toCharArray()) { if (map.get(c) == 1) return c; }.
📋

Examples

Inputswiss
Outputw
Inputredivider
Outputv
Inputaabbcc
OutputNo non repeating character found
🧠

How to Think About It

To find the first non repeating character, first count how many times each character appears in the string. Then, check the string from the start and pick the first character whose count is exactly one.
📐

Algorithm

1
Get the input string.
2
Create a map to store character counts.
3
Loop through each character and update its count in the map.
4
Loop through the string again and check the count of each character in the map.
5
Return the first character with count 1 or indicate none found.
💻

Code

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

public class FirstNonRepeatingChar {
    public static char findFirstNonRepeatingChar(String str) {
        Map<Character, Integer> charCount = new LinkedHashMap<>();
        for (char c : str.toCharArray()) {
            charCount.put(c, charCount.getOrDefault(c, 0) + 1);
        }
        for (char c : str.toCharArray()) {
            if (charCount.get(c) == 1) {
                return c;
            }
        }
        return '\0'; // null char if none found
    }

    public static void main(String[] args) {
        String input = "swiss";
        char result = findFirstNonRepeatingChar(input);
        if (result != '\0') {
            System.out.println("First non repeating character: " + result);
        } else {
            System.out.println("No non repeating character found");
        }
    }
}
🔍

Dry Run

Let's trace the input "swiss" through the code

1

Count characters

Map after counting: {s=3, w=1, i=1}

2

Find first with count 1

Check 's' count=3 (skip), 'w' count=1 (return 'w')

CharacterCount
s3
w1
i1
💡

Why This Works

Step 1: Counting characters

We use a LinkedHashMap to keep track of how many times each character appears, preserving order.

Step 2: Finding the first unique

We check characters in original order and pick the first with count exactly 1.

Step 3: Return result

If no character has count 1, we return a special value indicating no unique character.

🔄

Alternative Approaches

Using array for ASCII counts
java
public class FirstNonRepeatingChar {
    public static char findFirstNonRepeatingChar(String str) {
        int[] counts = new int[256];
        for (char c : str.toCharArray()) {
            counts[c]++;
        }
        for (char c : str.toCharArray()) {
            if (counts[c] == 1) {
                return c;
            }
        }
        return '\0';
    }

    public static void main(String[] args) {
        String input = "swiss";
        char result = findFirstNonRepeatingChar(input);
        if (result != '\0') {
            System.out.println("First non repeating character: " + result);
        } else {
            System.out.println("No non repeating character found");
        }
    }
}
Faster for ASCII but uses fixed size array, not suitable for Unicode.
Using two loops (brute force)
java
public class FirstNonRepeatingChar {
    public static char findFirstNonRepeatingChar(String str) {
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            boolean repeated = false;
            for (int j = 0; j < str.length(); j++) {
                if (i != j && str.charAt(j) == c) {
                    repeated = true;
                    break;
                }
            }
            if (!repeated) {
                return c;
            }
        }
        return '\0';
    }

    public static void main(String[] args) {
        String input = "swiss";
        char result = findFirstNonRepeatingChar(input);
        if (result != '\0') {
            System.out.println("First non repeating character: " + result);
        } else {
            System.out.println("No non repeating character found");
        }
    }
}
Simple but inefficient O(n²) time, not recommended for long strings.

Complexity: O(n) time, O(n) space

Time Complexity

The program loops through the string twice: once to count characters and once to find the first unique, so time is O(n).

Space Complexity

It uses extra space to store counts for each character, which can be up to O(n) in worst case.

Which Approach is Fastest?

Using a LinkedHashMap is efficient and preserves order; array counting is faster for ASCII but less flexible; brute force is slow and not recommended.

ApproachTimeSpaceBest For
LinkedHashMap countingO(n)O(n)General strings with order preservation
Array counting (ASCII)O(n)O(1)ASCII strings, faster but limited charset
Brute force two loopsO(n²)O(1)Very short strings or learning purpose
💡
Use a LinkedHashMap to keep character order while counting frequencies.
⚠️
Not preserving character order when counting frequencies, leading to wrong first unique character.