Reverse words in a string

easy

By - Aman Pareek

Last Updated - 28/08/2024

Problem Statement

Write a function that takes a sentence as input and reverses the order of the words in that sentence. The reversed sentence should maintain the original spacing between words and should not alter the characters within each word.

Example 1

Input: str = "Hey Aman is that correct way to reverse words of a string"

Output: "string a of words reverse to way correct that is Aman Hey"

Solution 1: Using split, reverse, and join

function reverseWordsUsingSplitReverseJoin(str) {
  return str.split(" ").reverse().join(" ");
} 

const str1 = "Hey Aman is that correct way to reverse words of a string";
reverseWordsUsingSplitReverseJoin(str1);  //output: string a of words reverse to way correct that is Aman Hey 

Solution 2: Using reduce

function reverseWordsUsingReduce(str) {
  return str.split(" ").reduce((reversed, word) => word + " " + reversed, "").trim();
} 

const str1 = "Hey Aman is that correct way to reverse words of a string";
reverseWordsUsingReduce(str1);  //output: string a of words reverse to way correct that is Aman Hey 

Solution 3: Using for loop and push

function reverseWordsUsingForLoopAndPush(str) {
  const words = [];
  let word = "";
  for (let i = 0; i < str.length; i++) {
    if (str[i] === " ") {
      words.push(word);
      word = "";
    } else {
      word += str[i];
    }
  }
  words.push(word);
  return words.reverse().join(" ");
} 

const str1 = "Hey Aman is that correct way to reverse words of a string";
reverseWordsUsingForLoopAndPush(str1);  //output: string a of words reverse to way correct that is Aman Hey 

Solution 4: Using for...of loop

function reverseWordsUsingForOfLoop(str) {
  const words = [];
  let word = "";
  for (const char of str) {
    if (char === " ") {
      words.push(word);
      word = "";
    } else {
      word += char;
    }
  }
  words.push(word);
  return words.reverse().join(" ");
} 

const str1 = "Hey Aman is that correct way to reverse words of a string";
reverseWordsUsingForOfLoop(str1);  //output: string a of words reverse to way correct that is Aman Hey 

Solution 5: Using split and map

function reverseWordsUsingSplitAndMap(str) {
  const words = str.split(" ");
  return words.map((word, index, array) => array[array.length - 1 - index]).join(" ");
} 

const str1 = "Hey Aman is that correct way to reverse words of a string";
reverseWordsUsingSplitAndMap(str1);  //output: string a of words reverse to way correct that is Aman Hey 

Solution 6: Using Array.from and forEach

function reverseWordsUsingArrayFromAndForEach(str) {
  const words = [];
  Array.from(str).forEach((char) => {
    if (char === " ") {
      words.push(words.pop().trim());
      words.push("");
    } else {
      if (words.length === 0) words.push("");
      words[words.length - 1] += char;
    }
  });
  words.push(words.pop().trim());
  return words.reverse().join(" ");
} 

const str1 = "Hey Aman is that correct way to reverse words of a string";
reverseWordsUsingArrayFromAndForEach(str1);  //output: string a of words reverse to way correct that is Aman Hey 

Solution 7: Using String.prototype.replace with a regular expression

function reverseWordsUsingReplaceRegex(str) {
  return str.replace(/(\S+)/g, (match, p1, offset, string) => {
    const words = string.match(/\S+/g);
    return words[words.length - 1 - words.indexOf(p1)];
  });
} 

const str1 = "Hey Aman is that correct way to reverse words of a string";
reverseWordsUsingReplaceRegex(str1);  //output: string a of words reverse to way correct that is Aman Hey 

Solution 8: Using split, filter, and reduce

function reverseWordsUsingSplitFilterReduce(str) {
  return str.split(" ")
            .filter(word => word.length > 0)
            .reduce((reversed, word) => word + " " + reversed, "")
            .trim();
} 

const str1 = "Hey Aman is that correct way to reverse words of a string";
reverseWordsUsingSplitFilterReduce(str1);  //output: string a of words reverse to way correct that is Aman Hey 

Solution 9: Using a stack data structure

function reverseWordsUsingStack(str) {
  const stack = [];
  let word = "";
  for (let i = 0; i < str.length; i++) {
    if (str[i] === " ") {
      stack.push(word);
      word = "";
    } else {
      word += str[i];
    }
  }
  stack.push(word);
  return stack.reverse().join(" ");
} 

const str1 = "Hey Aman is that correct way to reverse words of a string";
reverseWordsUsingStack(str1);  //output: string a of words reverse to way correct that is Aman Hey 

Solution 10: Using split, sort, and join with index manipulation

function reverseWordsUsingSplitSortJoin(str) {
  const words = str.split(" ");
  return words.sort((a, b) => words.length - words.indexOf(a) - (words.length - words.indexOf(b))).join(" ");
} 

const str1 = "Hey Aman is that correct way to reverse words of a string";
reverseWordsUsingSplitSortJoin(str1);  //output: string a of words reverse to way correct that is Aman Hey