Reverse Words in a String

MediumStringstwo pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a string s made of words separated by spaces. A word is a maximal run of non-space characters. s may have leading spaces, trailing spaces, and several spaces between words. Return a string containing the words in reverse order, joined by exactly one space, with no leading or trailing spaces. The characters inside each word keep their original order. Follow-up: if strings were mutable, could you do it in place with O(1) extra space (reverse the whole string, then reverse each word)?

Examples

Input: s = " hello big world "
Output: "world big hello"
Extra spaces are dropped and the three words come out reversed.
Input: s = "one"
Output: "one"
A single word is unchanged.

Constraints

  • 1 <= s.length <= 10^4
  • `s` contains English letters, digits, and spaces
  • `s` contains at least one word

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More two pointers problems