Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Find the first non repeating character in a given string

Objec­tive: Given a string, write an algo­rithm to find the first non repeat­ing char­ac­ter in it.


String input = " tutorial horizon"

Output: 'u'

String input = "aabbccadd"

Output: No non-repeating character found.


Naive approach: This prob­lem can be eas­ily solved using two nested loops. Take each char­ac­ter from the outer loop and check the char­ac­ter in rest of the string using inner loop and check if that char­ac­ter appears again, if yes then con­tinue else return that char­ac­ter.  Time com­plex­ity is O(N^2).

Bet­ter approach: Using extra space

  • Iter­ate the string from left to right.
  • Count the occur­rence of each char­ac­ter and store it in a map.
  • Iter­ate the string again from left to right and check if the char­ac­ter has count = 1 one in the map cre­ated in the pre­vi­ous step, if yes then return that character.
  • If none of the char­ac­ter has count = 1 in map, return null.

Com­plete Code:


First Non Repeating Character in 'tutorial horizon' is: u

You may also like...

  • lipsa patel

    The out­put says “No repeat­ing char­ac­ter found”.
    It should be “No non-repeating char­ac­ter found.”

    • tuto­ri­al­hori­zon

      Thanks lipsa. Cor­rected it

  • Rizwan Shaikh

    //O(n*2) com­plex­ity.

    pub­lic class First­Non­Re­peat­ingChar

    pub­lic sta­tic void main(String[] args)
    Linked­HashMap map = new Linked­HashMap();
    String input = “aab­bc­cadd”;
    char[] chars = input.toCharArray();
    for(char c : chars) {
    if(map.get© != null) {
    map.put(c, map.get© + 1);
    } else {
    map.put(c, 1);
    boolean found = false;
    for(char c : map.keySet()) {
    if(map.get© == 1) {
    found = true;
    if(!found) {
    System.out.println(“No non repeat­ing char­ac­ter found”);