Reverse Traversal Homework
Reverse Traversal Homework
Reverse Traversal Homework
Interview Camp
Solution:
We start from the back. As soon as we find a space separating words, we add that word to the result.
Pseudocode:
(Note: Never write pseudocode in an actual interview. Unless you're writing a
few lines quickly to plan out your solution. Your actual solution should be in
a real language and use good syntax.)
result = empty string
current_word_end = str.length
i -> str.length-1 to 0
if str[i] is a space:
extract str[i..current_word_end], add it to result
reset current_word_end to i;
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
Test Cases:
Corner Cases: null string, empty string, single letter, single space, begins with space, ends with space
Base Cases: one word, two words
Regular Cases: 5 words
Note: We use StringBuilder in Java to append Strings. in Java, just adding to Strings with a '+'
creates a new String, which is inefficient (strings are immutable).
This also impresses interviewers. In other languages, this might not be the case. Check if strings are
immutable in your language.
public static String reverseWords(String s) {
StringBuilder builder = new StringBuilder();
int currentWordEnd = s.length();
builder.append(s.substring(i+1, currentWordEnd));
currentWordEnd = i;
}
}
return builder.toString();
}
/*
* Notice that above, you used the following lines twice:
*
* if (builder.length() > 0)
* builder.append(' ');
* builder.append(firstWord);
*
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
* It is good to point that out. Mention that in the real world, you could
* extract them into a separate function.
*/
© 2017 Interview Camp (interviewcamp.io)