top of page

Reverse Words in a String

  • Shreyas Naphad
  • Jun 17, 2024
  • 1 min read

In this article, we will solve the problem of reversing the words in a given string.

Example:

Input: s = "the bloodline is cooking"

Output: "cooking is bloodline the"


Solution:


Explanation:

1.    Initialize Pointers:

o   start points to the beginning of the string.

o   end points to the end of the string.

2.    Iterate Through the String:

o   We use a while loop to traverse the string from the beginning to the end.

o   For each character, if it's not a space, we add it to the current word (word).

o   If a space is found, we then prepend the current word to the result (result) and reset the word to an empty string.

3.    Add the Last Word:

o   After the loop, if there is any word left in the word variable, we add it to the result.

 

Time Complexity: O(N)

Space Complexity: O(N)

Comments


©2025 by DevSparks.

bottom of page