Reverse words in a string (original) (raw)

Last Updated : 29 Oct, 2025

Given a string **s, find a way to reverse the order of the words in the given string.

**Note: string may contain leading or trailing dots(.) or multiple trailing dots(.) between two words. The returned string should only have a single dot(.) separating the words.

**Examples:

**Input: s = "i.like.this.program.very.much"
**Output: much.very.program.this.like.i
**Explanation: The words in the input string are reversed while maintaining the dots as separators, resulting in "much.very.program.this.like.i".

**Input: s = ”..geeks..for.geeks.”
**Output: geeks.for.geeks

**Input: s = "...home......"
**Output: home

Try It Yourselfredirect icon

Table of Content

**[Naive Approach] Using Stack - O(n) Time and O(n) Space

Push all words separated by dots into a stack, then pop each word one by one and append it back to form the reversed string.

C++ `

#include #include #include using namespace std;

string reverseWords(string &s) { stack st; string result = ""; for (int i = 0; i < s.length(); i++) {

    if (s[i] != '.') {
        result += s[i];
    }

    // If we see a dot, we push the
    // previously seen word into the stack.
    else if (!result.empty()) {
        st.push(result);
        result = "";
    }
}

// Last word remaining, add it to stack
if (!result.empty()) {
    st.push(s);
}

result = "";
// Now add from top to bottom of the stack
while (!st.empty()) {
    result += st.top();
    st.pop();
    if (!st.empty()) {
        result += ".";
    }
}
return result;

}

int main() { string s = "..geeks..for.geeks."; cout << reverseWords(s) << endl; return 0; }

Java

import java.util.Stack;

class GfG {

static String reverseWords(String s) {
    Stack<String> stack = new Stack<>();
    StringBuilder word = new StringBuilder();

    // Iterate through the string
    for (int i = 0; i < s.length(); i++) {

        // If not a dot, 
        // build the current word
        if (s.charAt(i) != '.') {
            word.append(s.charAt(i));
        }

        // If we see a dot, 
        // push the word into the stack
        else if (word.length() > 0) {
            stack.push(word.toString());
            word.setLength(0);  
        }
    }

    // Last word remaining,
    // push it to stack
    if (word.length() > 0) {
        stack.push(word.toString());
    }

    // Rebuild the string 
    // from the stack
    StringBuilder result = new StringBuilder();
    while (!stack.isEmpty()) {
        result.append(stack.pop());
        if (!stack.isEmpty()) {
            result.append(".");
        }
    }

    return result.toString();
}

public static void main(String[] args) {
    String s = "..geeks..for.geeks.";
    System.out.println(reverseWords(s));
}

}

Python

def reverseWords(s): stack = [] word = ""

# Iterate through the string
for ch in s:
    
    # If not a dot, build 
    # the current word
    if ch != '.':
        word += ch
    
    # If we see a dot, push 
    # the word into the stack
    elif word:
        stack.append(word)
        word = ""

# Last word remaining, 
# push it to stack
if word:
    stack.append(word)

# Rebuild the string from the stack
return ".".join(stack[::-1])

if name == "main": s = "..geeks..for.geeks." print(reverseWords(s))

C#

using System; using System.Collections.Generic;

class GfG {

static string reverseWords(string s) {
    Stack<string> stack = new Stack<string>();
    string word = "";

    // Iterate through the string
    for (int i = 0; i < s.Length; i++) {

        // If not a dot, build 
        // the current word
        if (s[i] != '.') {
            word += s[i];
        }

        // If we see a dot, push 
        // the word into the stack
        else if (word.Length > 0) {
            stack.Push(word);
            word = "";
        }
    }

    // Last word remaining, 
    // push it to stack
    if (word.Length > 0) {
        stack.Push(word);
    }

    // Rebuild the string from the stack
    string result = "";
    while (stack.Count > 0) {
        result += stack.Pop();
        if (stack.Count > 0) {
            result += ".";
        }
    }

    return result;
}

static void Main() {
    string s = "..geeks..for.geeks.";
    Console.WriteLine(reverseWords(s));
}

}

JavaScript

function reverseWords(s) { let stack = []; let word = "";

// Iterate through the string
for (let i = 0; i < s.length; i++) {

    // If not a dot, 
    // build the current word
    if (s[i] != '.') {
        word += s[i];
    }

    // If we see a dot, 
    // push the word into the stack
    else if (word.length > 0) {
        stack.push(word);
        word = "";
    }
}

// Last word remaining, 
// push it to stack
if (word.length > 0) {
    stack.push(word);
}

// Rebuild the string from the stack
return stack.reverse().join('.');

}

// Driver Code let s = "..geeks..for.geeks."; console.log(reverseWords(s));

`

**[Expected Approach] Using Two Pointer - O(n) Time and O(1) Space

Reverse the entire string, then iterate through it to extract words separated by dots. Reverse each word individually and update the original string until the end is reached. Refer to the figure to understand better...

C++ `

#include #include #include using namespace std;

string reverseWords(string s) {

// reverse the whole string
reverse(s.begin(), s.end());

int n = s.size();
int i = 0;
for (int l = 0; l < n; ++l) {
    if (s[l] != '.') {
      
        // go to the beginning of the word
        if (i != 0) s[i++] = '.';

        // go to the end of the word
        int r = l;
        while (r < n && s[r] != '.') s[i++] = s[r++];

        // reverse the word
        reverse(s.begin() + i - (r - l), s.begin() + i);

        // move to the next word
        l = r;
    }
}
s.erase(s.begin() + i, s.end());
return s;

}

int main() { string s = "..geeks..for.geeks."; cout << reverseWords(s) << endl; return 0; }

C

#include <stdio.h> #include <string.h>

// Function to reverse a string void reverse(char* begin, char* end) { char temp; while (begin < end) { temp = *begin; *begin++ = *end; *end-- = temp; } }

// Function to reverse words in a string char* reverseWords(char* s) {

// reverse the whole string
reverse(s, s + strlen(s) - 1);

int n = strlen(s);
int i = 0;
for (int l = 0; l < n; ++l) {
    if (s[l] != '.') {
      
        // go to the beginning of the word
        if (i != 0) s[i++] = '.';

        // go to the end of the word
        int r = l;
        while (r < n && s[r] != '.') s[i++] = s[r++];

        // reverse the word
        reverse(s + i - (r - l), s + i - 1);

        // move to the next word
        l = r;
    }
}
s[i] = '\0';
return s;

}

int main() { char s[] = "..geeks..for.geeks."; printf("%s\n", reverseWords(s)); return 0; }

Java

class GfG {

public static String reverseWords(String s) {
    // Convert the string to a char array 
    // for in-place operations
    char[] chars = s.toCharArray();
    int n = chars.length;

    // Reverse the entire string
    reverse(chars, 0, n - 1);

    int i = 0;
    for (int l = 0; l < n; ++l) {
        if (chars[l] != '.') {

            // Add a dot between words if needed
            if (i != 0) chars[i++] = '.';

            // Find the end of the word
            int r = l;
            while (r < n && chars[r] != '.') chars[i++] = chars[r++];

            // Reverse the current word
            reverse(chars, i - (r - l), i-1);

            // Move to next word
            l = r;
        }
    }

    return new String(chars, 0, i);
}

// Utility to reverse part of the char array
private static void reverse(char[] arr, int left, int right) {
    while (left < right) {
        char temp = arr[left];
        arr[left++] = arr[right];
        arr[right--] = temp;
    }
}

public static void main(String[] args) {
    String s = "..geeks..for.geeks.";
    System.out.println(reverseWords(s));
}

}

Python

def reverseWords(s):

# reverse the whole string
s = s[::-1]

n = len(s)
i = 0
result = []

l = 0
while l < n:
    if s[l] != '.':
      
        # go to the beginning of the word
        if i != 0:
            result.append('.')
            i += 1

        # go to the end of the word
        r = l
        while r < n and s[r] != '.':
            result.append(s[r])
            i += 1
            r += 1

        # reverse the word
        result[i - (r - l):i] = reversed(result[i - (r - l):i])

        # move to the next word
        l = r
    l += 1

return ''.join(result)

if name == "main": s = "..geeks..for.geeks." print(reverseWords(s))

C#

using System;

class GfG{ public static string reverseWords(string s){ // Convert the string to a char array // for in-place operations char[] chars = s.ToCharArray(); int n = chars.Length;

    // Reverse the entire string
    reverse(chars, 0, n - 1);

    int i = 0;
    for (int l = 0; l < n; ++l){
        if (chars[l] != '.'){
            // Add a dot between words if needed
            if (i != 0) chars[i++] = '.';

            // Find the end of the word
            int r = l;
            while (r < n && chars[r] != '.') chars[i++] = chars[r++];

            // Reverse the current word
            reverse(chars, i - (r - l), i);

            // Move to next word
            l = r;
        }
    }

    return new string(chars, 0, i);
}

// Utility to reverse part of the char array
private static void reverse(char[] arr, int left, int right){
    right--;  
    while (left < right){
        char temp = arr[left];
        arr[left++] = arr[right];
        arr[right--] = temp;
    }
}

static void Main(){
    string s = "..geeks..for.geeks.";
    Console.WriteLine(reverseWords(s));
}

}

JavaScript

function reverse(s, start, end) { while (start < end) { let temp = s[start]; s[start] = s[end]; s[end] = temp; start++; end--; } }

function reverseWords(s) {

// Convert the string to an array of characters
s = s.split('');

// reverse the whole string
reverse(s, 0, s.length - 1);

let n = s.length;
let i = 0;
for (let l = 0; l < n; ++l) {
    if (s[l] !== '.') {
    
        // go to the beginning of the word
        if (i !== 0) s[i++] = '.';

        // go to the end of the word
        let r = l;
        while (r < n && s[r] !== '.') s[i++] = s[r++];

        // reverse the word
        reverse(s, i - (r - l), i - 1);

        // move to the next word
        l = r;
    }
}
return s.slice(0, i).join('');

}

// Driver Code let s = "..geeks..for.geeks."; console.log(reverseWords(s));

`

[Alternate Approach] Using inbuilt library functions - O(n) Time and O(n) Space

We can efficiently solve this problem using built-in library functions like split to break the string into words, reverse to reverse the order of words, and stringstream (or equivalent functions) to reconstruct the final reversed string. This approach simplifies implementation and improves readability.

C++ `

#include #include #include #include #include using namespace std;

string reverseWords(string s) {

vector<string> words;
stringstream ss(s);
string word;

while (getline(ss, word, '.')) {
    if (!word.empty()) {
        words.push_back(word);
    }
}

reverse(words.begin(), words.end());

string result;
for (int i = 0; i < words.size(); ++i) {
    if (i > 0) {
        result += '.';
    }
    result += words[i];
}

return result;

}

int main() { string s = "..geeks..for.geeks."; cout << reverseWords(s) << endl; return 0; }

Java

import java.util.ArrayList; import java.util.Collections;

class GfG {

static String reverseWords(String s) {
    
    // Split the input string by '.' while 
    // ignoring multiple consecutive dots
    ArrayList<String> words = new ArrayList<>();
    String[] parts = s.split("\\.");
    
    for (String word : parts) {
        if (!word.isEmpty()) {
            
            // Ignore empty words caused 
            // by multiple dots
            words.add(word);
        }
    }
    
    // Reverse the words
    Collections.reverse(words);
    
    // Join the reversed words 
    // back into a string
    return String.join(".", words);
}

public static void main(String[] args) {
    String s = "..geeks..for.geeks.";
    System.out.println(reverseWords(s));
}

}

Python

def reverseWords(s):

# Split the input string by '.' while 
# ignoring multiple consecutive dots
words = [word for word in s.split('.') if word]

# Reverse the words
words.reverse()

# Join the reversed words 
# back into a string
return '.'.join(words)

if name == "main": s = "..geeks..for.geeks." print(reverseWords(s))

C#

using System; using System.Collections.Generic;

class GfG {

static string reverseWords(string s) {
    
    // Split the input string by '.' while 
    // ignoring multiple consecutive dots
    List<string> words = new List<string>();
    string[] parts = s.Split('.');

    foreach (string word in parts) {
        if (!string.IsNullOrEmpty(word)) {
            
            // Ignore empty words caused 
            // by multiple dots
            words.Add(word);
        }
    }

    // Reverse the words
    words.Reverse();

    // Join the reversed words 
    // back into a string
    return string.Join(".", words);
}

static void Main() {
    string s = "..geeks..for.geeks.";
    Console.WriteLine(reverseWords(s));
}

}

JavaScript

function reverseWords(s) {

// Split the input string by '.' while 
// ignoring multiple consecutive dots
const words = [];
const parts = s.split('.');

for (const word of parts) {
    if (word.length > 0) {
        
        // Ignore empty words caused 
        // by multiple dots
        words.push(word);
    }
}

// Reverse the words
words.reverse();

// Join the reversed words 
// back into a string
return words.join('.');

}

// Example usage const s = "..geeks..for.geeks."; console.log(reverseWords(s));

`