reverse word algorithm javascript

leetcode reverse word solution

In this article, I will explore reverse word algorithm javascript using the big O time complexity of O(n). Reverse word algorithm does exactly what its name says. REVERSE A WORD.

Consider the examples below:

Input: I am going to school
Output: school to going am I


Input: My name is simon jerry
Output: jerry simon is name My

Understanding the above examples, let’s see the implementation.

Question:

Giving an input string s, reverse the order of the words. Return a string of the word in reverse order concatenated by a single space.

Reverse Word pseudocode

  • Split the sentence into an array of words
  • Declare an array to hold reverse words.
  • Iterate the array of words backward.
  • In the loop, push each item into the declared array
  • After the loop, convert the array to a string and return

reverse word algorithm javascript implementation

  • Split the sentence into an array of words and declare to hold reverse words
const reverseWord = (str)=> {
    let stringOneWordArr = str.split(" ");
    // temp array to hold reverse stirng.
    let reverseWord = [];

    return reverseWord.join(" ")
}

Iterate the loop of words backward and push each item into the declared array.

const reverseWord = (str)=> {
    let stringOneWordArr = str.split(" ");
    // temp array to hold reverse stirng.
    let reverseWord = [];

  for ( let i = (stringOneWordArr.length)- 1; i >= 0; i--){
        //pushing the reverse word into an array
        reverseWord.push(stringOneWordArr[i]);

    }

    return reverseWord.join(" ")
}

Finally, convert the array to string and return

const reverseWord = (str)=> {
    let stringOneWordArr = str.split(" ");
    // temp array to hold reverse stirng.
    let reverseWord = [];

  for ( let i = (stringOneWordArr.length)- 1; i >= 0; i--){
        //pushing the reverse word into an array
        reverseWord.push(stringOneWordArr[i]);
    }

    return reverseWord.join(" ")
}

Run the code below, you should get the inputted word reversed

const reverseWord = (str)=> {
    let stringOneWordArr = str.split(" ");
    // temp array to hold reverse stirng.
    let reverseWord = [];

  for ( let i = (stringOneWordArr.length)- 1; i >= 0; i--){
        //pushing the reverse word into an array
        reverseWord.push(stringOneWordArr[i]);
    }

    return reverseWord.join(" ")
}

let str1 = "Javascript is Best";
console.log(reverseWord(str1)) //Best is Javascript

The above algorithm takes O(n) time complexity. You can find this reverse word algorithm javascript solution on my Github page.

You can try out your algorithm skill on leetcode or codewar

If you want to see more explanation on Big O notation

View related algorithm solution here

Leave a Reply

Your email address will not be published. Required fields are marked *