Microsoft Interview Question
how is that o(n) in time. You need to first go all the way to the end, which is O(n) itself. And if the last occurence of the character is the first letter itself (for example, last occurence of 'C' in "Cars are fast and expensive") , u hav to go all the way back to the beginning => O(n^2).
Nope O(1) is correct. If chars are stored in an array, you can jump to last element in O(1) time.
how can you jump to the last in O(1) time? you need to know the length of the string right? it takes O(n) time to find out the length of the string. As mentioned by JK, what if the char is at the beginning only? your solution is O(2n) but if you move from the start to end it is O(n) which is better than O(2n).
int lastOccurrence(char *str, char ch){
if(str==NULL)
return -1;
int pos=strlen(str)-1;
while( pos>=0 ){
if(str[pos]==ch)
break;
pos--;
}
return pos ;
}
int pos=strlen(str)-1; //WRONG
int pos=strlen(str); //RIGHT
// strlen excludes '\0' nul character//
o(1) space with o(n) time. Just start at the end of the sentance and scan to the beginning searching for the character. Optimal in regards to space and time.
- Anonymous February 18, 2007