Background
This is a question which usually gets asked in many programming interviews. One of my friends was asked this question in his Microsoft Interview and he answered it. Here is his experience in my words.
Tip!! When you face such question in interview, never hesitate to mention the solution that seems obvious to you.

Obvious Solution
Starting with first character of string, keep comparing this with all other characters in the string unless you find a non-repetitive one. But tell your interviewer that it is most trivial and Although you can optimize this solution by either comparing a character with the characters to the right of it, because this way you are removing redundant comparisons. But in both the cases, worst case complexity is going to be O(n^2). So tell your interviewer that you are looking for a better solution.

Maintaining a Count Array
A good solution may be if we can have an array which maintains count for number of times a character appears in the string and this array can be filled in O(n) by going once through the string. And once we are done with it, we can again parse whole string and find the first character that has count 1. Wow!!! This one requires two passes through whole string so it will take 2n time. Which is obviously O(n). If your interviewer is impressed with this approach then proceed further with the implementation of the algorithm.

int charCount[128];

char firstNonRepeatingChar(const char* string)
{
int i=0;

//Keep count
while(string[i]!='\0')
{
charCount[string[i]] += 1;
i++;
}

i=0;

//Find Character
while(string[i]!='\0')
{
if(charCount[string[i]] == 1)
return string[i];
i++;
}

return '-';
}

Special Note: Ask interviewer what does he want if all characters are repeated? In my case, interviewer told me, your function should return '-' in that case as they don't expect '-' to be one of the characters in the string.
But this is not where a tough interviewer will stop. Why??
Extra Space: Because you are using an array to store count of characters which will be of size 128 as there are 128 ASCII characters but if you are dealing with Unicode then this length will be 65536.
Optimize: Interviewer may ask you if you can make it n from 2n?

1 comments

  1. pavan // March 20, 2009 at 8:05 PM  

    Thank your. It was helpful to me. Is it possible to make it to n from 2n? What is the solution?