Skip to content

Instantly share code, notes, and snippets.

@Ephraimiyanda
Created January 18, 2026 23:38
Show Gist options
  • Select an option

  • Save Ephraimiyanda/745cef1d23a27886b2451c0bac5be6c4 to your computer and use it in GitHub Desktop.

Select an option

Save Ephraimiyanda/745cef1d23a27886b2451c0bac5be6c4 to your computer and use it in GitHub Desktop.
Reverse Words in a String

Question

Approach

  1. The string us turned into an array.
  2. All the spaces in the array are removed in a loop.
  3. The words are the added into an array from the last to the first so that its in a reversed order.
  4. I use the join operator to add words together with single spaces

Complexity

  • Time complexity: O(N)

  • Space complexity: O(N)

Code

function reverseWords(s: string): string {
    let strings = s.split(" ")
    let reversedWords = []
    let i = 0;
    while (i <strings.length) {
        let letters = strings[i]
        if (letters.length !== 0) {
            reversedWords.unshift(strings[i])
        }
        i++
    }
    return reversedWords.join(" ")
};
scrnli_xwvOZ2BI4dLSMg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment