Find first non repeating character in a string

You are given a string, find its first non-repeating character?

Algorithm:

1) Scan the string from left to right and construct the count array.
2) Again, scan the string from left to right and check for count of each
character, if you find an element who’s count is 1, return it.

#include<stdlib.h>
#include<stdio.h>
#define NO_OF_CHARS 256

/* The function returns index of first non-repeating
   character in a string */
int getFirstNonRepeating(char *str)
{
	int *count = (int *)calloc(sizeof(int), NO_OF_CHARS);
	int i;
	for (i = 0; *(str+i);  i++)
	  count[*(str+i)]++;
	int index = -1;

	for (i = 0; *(str+i);  i++)
	{
		if(count[*(str+i)] == 1)
		{
		  index = i;
		  break;
		}
	}
	return index;
}

Time complexity: O(N)

4 Thoughts on “Find first non repeating character in a string

  1. Purushottam Ray on April 13, 2014 at 5:30 am said:

    consider arrayoutofindex case here. rather than puting directly using *(str+i) like this use *(str+i)-offset, here offset might be 65(ascii value if A or 97 ascii value of a) if the string contains only alphabets.

  2. Tarun on June 27, 2015 at 7:31 pm said:

    public class nonRep {
    public static void main(String[] args) {
    String s1=”asdfas” ;
    char [] arr=new char[256];

    for(int i=0;i<s1.length();i++)
    {
    arr[s1.charAt(i)]++;
    }
    for(int i=0;i<256;i++)
    {

    if(arr[i] == 1)
    {
    System.out.printf("%c",i);
    break;

    }
    }

    }
    }

  3. s1.charAt(i) returns a character how can a character be index of an array please explain

Leave a Reply to Tarun Cancel reply

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>

Post Navigation