Subj : Re: Reverse words in a string (Another Interview question) To : comp.programming From : Roger Willcocks Date : Thu Sep 29 2005 11:30 pm "Jaspreet" wrote in message news:1128011781.932340.25490@o13g2000cwo.googlegroups.com... > 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 ? .... > As an interviewer, I'd hope the first response was 'how do you define a word?'. Then 'do you want the whitespace folded?'. Then 'do you just want to just output the words, or will you want to process them further?' One perfectly good answer would be: #include void main(int argc, char* argv[]) { while (argc > 1) printf("%s ", argv[--argc]); } -- Roger .