Reverse words in a string

easy

By - Aman Pareek

Last Updated - 21/09/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 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 

This function splits the input string into an array of words, then uses the reduce method to concatenate these words in reverse order. The final result is trimmed to remove any leading or trailing spaces.

Solution 2: 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 

This straightforward function splits the string into an array of words, reverses that array, and then joins the words back together with spaces. It effectively reverses the word order with minimal code.

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 

Here, a for loop iterates over each character of the string, building words and pushing them into an array whenever a space is encountered. After processing, the array of words is reversed and joined to form the final output.

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 

Similar to the previous function, this one uses a for...of loop to iterate through each character. It constructs words based on spaces and stores them in an array, which is then reversed and joined.

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 

This function splits the string into words and utilizes the map method to create a new array where each word is positioned in reverse order. The words are then joined back together with spaces.

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 

Using Array.from to convert the string into an array of characters, this function iterates with forEach. It constructs words while tracking spaces and ultimately reverses the array of words before joining.

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 

This advanced function employs a regular expression with the replace method. It matches non-space sequences and returns them in reverse order by accessing their indices in the original string.

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 

This function splits the string into words, filters out any empty strings (to handle extra spaces), and then uses reduce to concatenate the words in reverse order. It returns a trimmed result.

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 

By utilizing a stack (LIFO structure), this function pushes words onto the stack when a space is encountered. After processing the string, it reverses the stack and joins the words to get the final output.

Solution 10: Sliding Window Approach to Reverse Words in a String

function reverseWordsSlidingWindow(s) {
    let result = "";
    
    // Return an empty string if input is empty or just whitespace
    if (s.length === 0 || s.trim() === "") {
        return result;
    }

    // If the string is just one character in length, return it
    if (s.length === 1) {
        return s;
    }

    // Extract the words using the GetWords function
    const words = getWords(s);

    // Reassembly of the words
    result = words.join(" ") + " ";

    // Trim the trailing space before returning
    return result.trimEnd();
}

function getWords(s) {
    const words = [];
    let i = s.length - 1, j = i;

    while (i >= 0) {
        // If current char is whitespace and the next is not
        if (s[i] === ' ' && s[i - 1] !== ' ') {
            j = i; // Mark end of word
        } 
        // If current char is not whitespace and the next is whitespace
        else if (s[i] !== ' ' && s[i - 1] === ' ') {
            // Extract the word
            if (j === s.length - 1 && s[j] !== ' ') {
                words.push(s.substring(i));
            } else {
                words.push(s.substring(i, j));
            }
        }
        // Handle the case when the last character is not whitespace
        if (i === 0 && s[i] !== ' ') {
            words.push(s.substring(i, j + 1));
        }
        i--;
    }

    return words;
} 

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

This function extracts words using a custom getWords function, handling edge cases like empty or whitespace-only strings. It constructs the result by joining the extracted words while maintaining their order.

Solution 11: 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 

This function splits the string into words, sorts them based on their original indices in reverse order, and then joins them back together. This is a more unconventional approach to achieving the same result.

Solution 12: Two-Pointer Approach to Reverse Words in a String

function reverseWordsTwoPointer(str) {
    const n = str.length;
    let ans = "";
    if (n === 0) return "";
    let temp = "";

    for (let i = 0; i < n; i++) {
        if (str[i] !== ' ') {
            temp += str[i];
        }

        if (str[i] === ' ' && temp.length !== 0) {
            ans = ans.length !== 0 ? temp + " " + ans : temp;
            temp = "";
        }
    }

    // Handle the last word
    if (temp.length !== 0) {
        ans = ans.length !== 0 ? temp + " " + ans : temp;
    }

    return ans.trim(); // Trim any leading or trailing spaces
} 

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

This two-pointer method iterates through the string, collecting characters for words. It constructs the reversed sentence by appending each word in reverse order, ensuring spaces are handled correctly.

Solution 13: Divide and Conquer

function reverseWordsDivideConquer(s) {
    const words = s.trim().split(/\s+/); // Split by whitespace and trim input
    let reversed = "";

    // Construct the reversed string by appending words in reverse order
    for (let i = words.length - 1; i >= 0; i--) {
        if (reversed) {
            reversed += " "; // Add a space if not the first word
        }
        reversed += words[i];
    }

    return reversed;
} 

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

Using a divide-and-conquer approach, this function trims and splits the string by whitespace. It then constructs a reversed string by appending words in reverse order, which is efficient for handling larger inputs.

Resources

Frequently asked questions

  1. How do you reverse a word in a string?

    To reverse a word in a string, you can split the string into individual words, reverse the characters of the specific word, and then join the words back together. This can be done using loops, recursion, or built-in methods in various programming languages.

  2. How do you go backwards in a string?

    To traverse a string backwards, you can use a loop that starts from the last character and moves towards the first. For example, by using a for loop that decrements the index, you can access each character in reverse order.

  3. Can you use reverse() on a string?

    Most programming languages treat strings as immutable, meaning you can't directly apply a reverse() method on them. Instead, you typically convert the string to an array or list, apply reverse(), and then convert it back to a string.

  4. How do you reverse a string without using reverse()?

    You can reverse a string without using reverse() by constructing a new string in reverse order. This can be done by iterating through the original string from the end to the beginning and appending each character to a new string. Alternatively, you could use a two-pointer approach to swap characters in place until you reach the middle of the string.

  5. How do you maintain original spacing while reversing words?

    To maintain original spacing, ensure you track the positions of spaces in the input string. After reversing the words, reinsert spaces at their original indices. This can involve using temporary arrays or additional string manipulation.

  6. Can you reverse words in a sentence with punctuation?

    Yes, you can reverse words while keeping punctuation intact by treating punctuation as part of the word or separating it appropriately during the word-splitting process. Ensure your algorithm accounts for punctuation when joining the reversed words.

  7. How do you reverse words in a string in Java without using the split function?

    To reverse words in a string without using the split function, you can iterate through the string character by character, building words based on spaces. You can store these words in a list or array, and then reverse the order of the words before constructing the final output. This approach allows you to handle spacing correctly while avoiding the use of split. For example, you can utilize a loop to collect characters into words, then join them in reverse order.

  8. How to practice for Reverse words in a string leetcode problem and solve?

    You can effectively practice this LeetCode problem by utilizing the solutions provided above. Each solution has been tested to ensure functionality before being included, giving you a reliable foundation to build upon. Try implementing these methods in your own code, experimenting with different inputs and edge cases to deepen your understanding.

Popular Solutions