I haven't read the other answers simply because I want to give it a go myself.
Let's iteratively improve our solution.
Our analysis in terms of time and space complexity will require us to state a few things clearly at first:
Let
N = length of string
M = numbers of characters in alphabet
Brute force algorithm is to traverse the string and for each element of string we search to its right to see if it has a duplicate.
Time Complexity:O(N2)
Space Complexity:O(1)
Can we do better?
Sure, we can traverse the string and make count of many times a character appears.Make another traversal through the string to find the first character that has count 1.
Time Complexity:O(N+M)
Space Complexity:O(M)
Why is this O(N+M)?
Because we need to initialize the elements of the count array to 0 first.So even if input is "a", we need to initialize the count array for M elements.
Can we do better?
First let's state to the interviewer that this task is Omega(N), simply because we have to see each element of the string atleast once.Realize this by seeing a input instance of "aaaaaaz"
So we are not aiming to better our time complexity, simply making the actual running time better by doing just one traversal through the string.
This is indeed possible.
for(int i=0;i<N;i++)
{
if(visited[i]==-2)continue;
if(visited[i]==-1)visited[i]=i;continue;
visited[i]=-1;
}
int F=N;
char res=' ';
for(int i=0;i<M;i++)
{
if(visited[i]>=0)
{
F=min(F,visited[i]);
res=A[visited[i]];
}
}
return res;
Time Complexity:O(N+M)
Space Complexity: O(M)
Can we do better?
Can we do this in O(N) perhaps?
I'm still thinking of a way to do this in true O(N).IF I hit upon a solution, I will update this answer.