First Not Repeating Character in String - The Coding Shala

Home >> Interview Questions >> First Not Repeating Character

 In this post, we will learn how to find the First Not Repeating Character in a String and will write a Java program for the same.

First Not Repeating Character in a String

Given a string s consisting of small English letters, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'.

Example 1:
For s = "abacabad", the output should be firstNotRepeatingCharacter(s) = 'c'.
There are 2 non-repeating characters in the string: 'c' and 'd'. Return c since it appears in the string first.

Example 2:
For s = "abacabaabacaba", the output should be firstNotRepeatingCharacter(s) = '_'.
There are no characters in this string that do not repeat.

First Not Repeating Character in a String Java Program

Approach 1

We will use HashMap to count the occurrence of each character then will return if the count of a char is 1.

Java Program: 

char firstNotRepeatingCharacter(String s) {
char[] arr = s.toCharArray();
HashMap<Character, Integer> map = new HashMap<>();
for(int i=0;i<arr.length;i++){
    if(map.containsKey(arr[i])){
        map.put(arr[i], map.get(arr[i])+1);
    }
    else{
        map.put(arr[i], 1);
    }
}
for(int i=0;i<arr.length;i++){
    if(map.get(arr[i])==1) return arr[i];
}
return '_';
}

Approach 2

We can use String methods indexOf() and lastIndexOf(). If both the methods return the same index that means char occur only once in the string.

Java Program: 

char firstNotRepeatingCharacter(String s) {
    char[] arr = s.toCharArray();
    for(int i=0;i<arr.length;i++){
        if(s.indexOf(arr[i])==s.lastIndexOf(arr[i])) return arr[i];
    }
    return '_';
}

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala

Java Program to Reverse a String using Stack - The Coding Shala