← Create New Paste

Reverse Words in a String: The Three-Reversal Trick Interviewers Love

4 views
"Reverse the words in a sentence" sounds like a warm-up, and that is exactly why it is dangerous. Interviewers use it to see whether you clarify requirements, handle messy input, and know the in-place technique that also solves "rotate an array by k". Here is how to work through it cleanly. 1. Clarify before you code Ask three questions first: - Can the input have leading, trailing, or multiple spaces between words? (Usually yes, and the output should have single spaces with no padding.) - What counts as a word? Normally any run of non-space characters. - Do they want O(1) extra space? In languages with immutable strings this means working on a character array. Saying these out loud shows the interviewer you think about edge cases before they force you to. 2. The simple version In Python the readable answer is: def reverse_words(s): return " ".join(reversed(s.split())) split() with no argument collapses runs of whitespace, so " the sky is blue " becomes "blue is sky the". This is O(n) time and O(n) space. Give this first, then say you can do it in place if they want. 3. The in-place three-step reversal Treat the string as a mutable array of characters: - Reverse the entire array. "the sky is blue" becomes "eulb si yks eht". - Walk through and reverse each word individually. "eulb" becomes "blue", "si" becomes "is", and so on. - Compact the spaces with a read pointer and a write pointer so only single spaces remain, then trim the end. def reverse(a, i, j): while i < j: a[i], a[j] = a[j], a[i] i += 1; j -= 1 Each character is touched a constant number of times, so the total is O(n) time and O(1) extra space beyond the array. 4. Why this matters: rotate array The same idea solves "rotate an array to the right by k". Reverse the whole array, reverse the first k elements, then reverse the rest. Remember k = k % n first, or k larger than the length will break your indices. Interviewers often ask this as a follow-up, and recognising the shared pattern is a strong signal. 5. Common mistakes - Forgetting to collapse multiple spaces, which produces "blue is sky". - Off-by-one errors when a word ends at the last index; handle the final word after the loop. - Using split(" ") instead of split(), which keeps empty strings for repeated spaces. 6. Talk through a dry run Before saying "done", trace one tricky input such as " a b " out loud. That catches the space-handling bugs that cost most candidates this problem. If you want feedback while you practice, or support during the real conversation, Linkjob AI (https://linkjob.ai) gives real-time help during live job interviews and technical interviews, including reminders to clarify input rules and test edge cases before you finish.
Created Nov 17, 2026 06:29 Expires Nov 17, 2027 06:29