PPractick

DSA interview question

Reverse the Words in a String (and Check a Palindrome)

Medium · Algorithms · Topics: string, two pointer

The problem

A voice assistant sometimes produces sentences with the words in the wrong order and messy spacing, like " hello world ". A clean-up step must reverse the order of the words, remove leading and trailing spaces, and leave exactly one space between words. The same text utilities module also needs a palindrome check that ignores punctuation and case, so that "A man, a plan, a canal: Panama" counts as a palindrome. Both are two-pointer string problems, and word reversal has a neat O(1)-extra-space trick: reverse the whole string, then reverse each word back.

Example: "the sky is blue" → "blue is sky the".

Function signature

string reverseWords(string s);        // single spaces, no leading or trailing spaces
bool isPalindrome(const string& s);   // letters and digits only, case-insensitive

Test cases

InputOutputExplanation
reverseWords("the sky is blue")"blue is sky the"
reverseWords(" hello world ")"world hello"Leading and trailing spaces removed
reverseWords("a good example")"example good a"Multiple spaces collapse to one
reverseWords("single")"single"
reverseWords(" ")""Only spaces
isPalindrome("A man, a plan, a canal: Panama")trueIgnoring punctuation and case
isPalindrome("race a car")false
isPalindrome(" ")trueNo letters or digits: an empty string is a palindrome

(Confirm: words are separated by spaces only; the palindrome check considers letters and digits and ignores case.)

How interviewers phrase it

Clarifying questions to ask

  1. Can there be leading, trailing or repeated spaces? How should they be handled?
  2. Is modifying the input string allowed? (In C++ it's mutable; in Java/Python strings are immutable.)
  3. For the palindrome: which characters count, and is it case-sensitive?

Follow-ups to expect

  1. "How do you do it in O(1) extra space?"
  2. "Why does reversing twice work?"
  3. "What's the simpler approach?"
  4. "How does the palindrome check handle punctuation?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in