Skip to problem
←

Reverse Words in a String

Medium 0 attempts

Given a string s containing English letters, digits, and ordinary spaces, return its words in reverse order. A word is a maximal run of non-space characters.

Keep the characters and their case inside each word unchanged. Separate output words with exactly one space, removing all leading, trailing, and repeated separator spaces.

For " hello world ", return "world hello". For "Code 123", return "123 Code"; do not reverse the letters or digits inside the words. If the input contains only spaces, return "".

Function contract

Implement reverseWords(s).

Output: Return the words in reverse order, separated by single spaces with no leading or trailing spaces. Return an empty string when the input has no words.

Example 1

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

Example 2

Input
s = "  hello   world  "
Output
"world hello"
Constraints
  • 1 <= s.length <= 10^4
  • s contains English letters, digits, and spaces

Scan Words from Right to Left

Start at the end of the string. Skip spaces, then scan left across the next word. Copy that word in its original character order into a result array, and continue from the preceding space.

The scan discovers words in reverse order without reversing their characters. Joining the collected words with one space normalizes every separator. When the input contains only spaces, no words are collected and joining the empty array returns an empty string.

javascript
function reverseWords(s) {
  const words = [];
  let i = s.length - 1;
  while (i >= 0) {
    while (i >= 0 && s[i] === " ") i--;
    if (i < 0) break;
    const end = i + 1;
    while (i >= 0 && s[i] !== " ") i--;
    words.push(s.slice(i + 1, end));
  }
  return words.join(" ");
}

Time: O(n) for scanning and joining | Space: O(n) for the collected words and result. JavaScript strings are immutable, so this is not an in-place string operation.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript