Microsoft Interview Question
Software Engineer / DevelopersSince there is no restriction to use string class function, strtok() can be used.
But if not then do (crude method)
F(char* iStr, char* List)
{
int i = strlen(iStr);
int j = 0 ;
for( k = 0 ; k < strlen(List) ; k++)
for( j = 0 ; j < i ; j++)
if(iStr[j] == List[k])
{
iStr[j] = iStr[j+1];
iStr[j+1] = ' ';
j += 1;
}
}
Complexity O(strlen(List) * strlen(iStr))
Sort the list of input characters that need to be deleted. and then binary search each char in the input string.
Say if
m = length of the list of characters to be deleted.
n = number of characters in original list.
Step 1) O( nlog(m) ) for sorting
Step 2) O ( n * log(m) ) for search
Overall : O( n log (m) )
Store the chars to be deleted in a Hash Map. Initialize the counter i,j=0;
i: Loop though the i/p string.
If the char exists in the Hash Map, increment i
If the char does not exist in the Hash Map copy arr[j]= arr[i]; increment i,j
Put a '\0'at the jth location of the i/p string
For reversing the normal recursive code
<pre lang="c" line="1" title="CodeMonkey31292" class="run-this">#include <stdio.h>
- Anonymous August 08, 2010void RemoveCharacters(char[], char[]);
int main(void) {
char input[] = "This program removes specified characters from a string";
char remove[] = "aeiou";
RemoveCharacters(input, remove);
return 0;
}
void RemoveCharacters(char input[], char* remove)
{
int i = 0;
char bitmap[256] = {NULL};
while(remove[i])
{
bitmap[remove[i]] = 1;
i++;
}
int write = 0, curr = 0;
while(input[curr])
{
if(!bitmap[input[curr]])
{
input[write] = input[curr];
write++;
}
curr++;
}
input[write] = NULL;
printf("%s", input);
}
</pre><pre title="CodeMonkey31292" input="yes">
</pre>