How do you reverse words in a given string?
This basic string manipulation question tests your familiarity with string parsing and in-place reversal techniques.
Why Interviewers Ask This
It serves as a warm-up to check coding fluency and attention to detail. Interviewers assess how you handle whitespace and word boundaries. It also reveals your ability to choose between built-in functions and manual implementation.
How to Answer This Question
Clarify if leading/trailing spaces should be preserved. Propose splitting by spaces, reversing the list, and joining. Or reverse the whole string then reverse individual words. Discuss edge cases like multiple spaces. Compare readability vs performance.
Key Points to Cover
- String splitting and joining
- List reversal
- Handling whitespace
- Alternative in-place method
Sample Answer
I will split the string by spaces into a list of words. Then reverse the list and join them back with a single space. This handles extra spaces naturally. Alternatively, I could reverse the entire string and then reverse each word individually to achieve the same result in-place.
Common Mistakes to Avoid
- Not handling multiple consecutive spaces
- Modifying the string incorrectly
- Forgetting to trim leading/trailing spaces
Practice This Question with AI
Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.
Related Interview Questions
How do you implement binary search on a sorted array?
Easy
MicrosoftWhat is Object-Oriented Programming in Java and why is it important?
Easy
GoogleHow do you add two numbers represented by linked lists?
Medium
AmazonWrite Selenium and Java code to automate an Amazon search
Medium
InfosysHow do you implement a queue using two stacks?
Medium
Goldman SachsHow do you flatten a linked list with random pointers?
Hard
Goldman Sachs