Reverse words in a string (Another Interview question)



Hi All

Just had another interview with those same questions which hardly make
a sense except this one probably.

I was asked to reverse the words in a string. Say if we have "Welcome
to google groups", I need to have it reversed to "groups google to
Welcome".

I told the interviewer that we could keep each word in a node in a
linked list and then try to reverse the linked list. That is:

--Original linked list
Welcome -> to -> google -> groups
--After reversing
groups -> google -> to -> Welcome

I guess the interviewer had learnt/used something else. He wanted me to
try reversing it inline that is without the option of using another
linked list. He probably wanted me to do something similar to - First
reverse the whole string and then individually reverse the words

a) Reverse the string to get:
spuorg elgoog ot emocleW

b) then reverse the individual words to get:
groups google to Welcome.

Now agreed my solution would take up extra memory but am not sure which
one is a faster and more efficient solution. I did the mistake of
telling the interviewer that the solution he thinks of is slightly
slower and in-efficient to code or go through by future programmers
which I am sure he did not like.

I would like an opinion on this from you. Which one is a better and a
more efficient solution ?

Please let me know. I guess thats fine with you.

Apologies for such a long post.

.


Quantcast