21. Reverse Words in a String

21. Reverse Words in a String

Medium
44.0%
1.6k
stringstacktwo-pointers
Google, Amazon, Netflix, Meta (Facebook), Apple, Microsoft, Uber, Bloomberg, Airbnb, Stripe, Adobe, Salesforce, LinkedIn, Oracle

You’re interviewing for a backend or data engineering role at a FAANG-level company. The interviewer describes a real product scenario:

A large search, messaging, or content management platform stores user-generated text such as queries, comments, and messages. Over time, these text inputs may contain inconsistent spacing, leading or trailing spaces, or multiple spaces between words.

For normalization and indexing purposes, the platform needs to reverse the order of words in a sentence while ensuring the output follows strict formatting rules.

The input text is represented as a string s.
The platform wants to reverse the words so that the last word appears first, and the first word appears last, with exactly one space separating each word.

This is a common practice coding problem for DSA question might ask in Google, Amazon, Netflix, Meta, Apple, Microsoft, Uber, and Bloomberg interviews.

Your Task

Given a string s, return a string where:

  • The words appear in reverse order
  • Words are separated by a single space
  • There are no leading or trailing spaces in the result

A word is defined as a sequence of non-space characters.

Input Format

  • s: a string containing words and spaces

Output Format

  • A string with the words reversed and properly formatted

Examples

Example 1:

Input: s = "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: s = " hello world "
Output: "world hello"

Example 3:

Input: s = "a good example"
Output: "example good a"

Constraints

  • 1 <= s.length <= 100,000
  • s contains English letters, digits, and spaces
  • There may be multiple spaces between words

Loading editor...

"the sky is blue"
"blue is sky the"

Console Output

Click "Run Code" or "Submit" to see results

Your code will be evaluated by AI with instant feedback