Java - Program to find the first non repeated character in a string


Input - codeforeach , Output - d
Input - principles , Output - r

Pseudo Algorithm

1) Build a map consisting of each character of string with repetition count.
i) Loop through the string characters
ii) For each character,
if the character key is found in the map
increment the value by 1
set the value to 1
2) Loop through the map to find the key ( character ) having value 1. If no key has value 1, return null.


import java.util.HashMap;

public class FirstNonRepeatedChar {
        public static void main(String[] args) {
                String input = "codeforeach";
                System.out.println(input + " : " + findFirstNonRepeatedChar(input));
        public static Character findFirstNonRepeatedChar(String input) {
                HashMap<Character, Integer> countMap = new HashMap<>();
                Character firstNonRepeatedChar = null;
                // Build the count map which stores characters and repetition count
                char tempChar;
                for(int i=0; i<input.length(); i++) {
                        tempChar = input.charAt(i);
                // find the character with value 1
                for (int i = 0; i < input.length(); i++) {
                        tempChar = input.charAt(i);
                        if(countMap.get(tempChar) == 1) {
                                firstNonRepeatedChar = tempChar;
                return firstNonRepeatedChar;


codeforeach : d



Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>