Microsoft Interview Question
Software Engineer in TestsI agree with Pranav, as per the question input (S1 and S2) the answer is 'b'.
The time complexity of Pranav's solution is O(N^2) [ for each char of S1 traverse each char of S2].
Are we allowed to take any other data structure ? the question doesn't talk about it.
Let's say we are allowed to then we can take a HashTable and we will traverse S2 and the persist each char as key, and their position as value. [ in case of duplicate occurance the first one will get place in the HashTabe ].
And then we will traverse S1 and for each char we will do a lookup in the HashTabe ( which is O(1) ). so we will be able to solve this problem in O(N) time compleixty with extra memory[ the HashTable ].
My question is if the ist character of S1 string has two or three occurances in S1. In That scenario, do we have to tell all the occurance or just the ist occurance.
The above code will work for the ist occurance.
1. Two strings s1[m], s2[n]. Take temp array A[26]
2. initialize all elements in A[26] to -1 ;
3. for each i=0 to n in S2[n]
if( A[ S2[i] - 'a' ] == -1 )
A[ S2[i] - 'a' ] = i;
4. Now temp array A[26] contains S2[] elements first indexes .
5. Take first element in S1[j] and look in Temp array (A[ S1[j]- 'a' ]), from temp array you will get first index in S[].
6. Time complexity O(n) & Space complexity O(1).
Siva - You solution looks excellent but I am not clear about your 5th point. What is the meaning of first index? Can you please give me some expamplary idea to make me more clear.
according to the question 'b' appears first in both s1 and s2
- pranav December 05, 2010int fn(s1,s2)
{
char a,b;
int i=j=0;
while(s1)
{
a=s1[i++];
while(s2)
{
j=0;
b=s2[j++];
if (a==b)
retun j;
break;
}
}
return -1;
}