Reverse words in a given string | Set 2
Last Updated :
12 Jul, 2025
Given string str, the task is to reverse the string by considering each word of the string, str as a single unit.
Examples:
Input: str = “geeks quiz practice code”
Output: code practice quiz geeks
Explanation:
The words in the given string are [“geeks”, “quiz”, “practice”, “code”].
Therefore, after reversing the order of the words, the required output is“code practice quiz geeks”.
Input: str = “getting good at coding needs a lot of practice”
Output: practice of lot a needs coding at good getting
In-place Reversal Approach: Refer to the article Reverse words in a given string for the in-place reversal of words followed by a reversal of the entire string.
Time Complexity: O(N)
Auxiliary Space: O(1)
Stack-based Approach: In this article, the approach to solving the problem using Stack is going to be discussed. The idea here is to push all the words of str into the Stack and then print all the elements of the Stack. Follow the steps below to solve the problem:
- Create a Stack to store each word of the string str.
- Iterate over string str, and separate each word of str by a space delimiter.
- Push all the words of str into the stack.
- Print all the elements of the stack one by one.
Below is the implementation of the above approach:
C++
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to reverse the words
// of a given string
void printRev(string str)
{
// Stack to store each
// word of the string
stack<string> st;
// Store the whole string
// in string stream
stringstream ss(str);
string temp;
while (getline(ss, temp, ' ')) {
// Push each word of the
// string into the stack
st.push(temp);
}
// Print the string in reverse
// order of the words
while (!st.empty()) {
cout << st.top() << " ";
st.pop();
}
}
// Driver Code
int main()
{
string str;
str = "geeks quiz practice code";
printRev(str);
return 0;
}
Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG{
// Function to reverse the words
// of a given String
static void printRev(String str)
{
// Stack to store each
// word of the String
Stack<String> st = new Stack<String>();
// Store the whole String
// in String stream
String[] ss = str.split(" ");
for (String temp : ss)
{
// Push each word of the
// String into the stack
st.add(temp);
}
// Print the String in reverse
// order of the words
while (!st.isEmpty())
{
System.out.print(st.peek() + " ");
st.pop();
}
}
// Driver Code
public static void main(String[] args)
{
String str;
str = "geeks quiz practice code";
printRev(str);
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program to implement
# the above approach
# Function to reverse the words
# of a given string
def printRev(strr):
# Stack to store each
# word of the string
strr = strr.split(" ")
st = []
# Store the whole string
# in stream
for i in strr:
# Push each word of the
# into the stack
st.append(i)
# Print the in reverse
# order of the words
while len(st) > 0:
print(st[-1], end = " ")
del st[-1]
# Driver Code
if __name__ == '__main__':
strr = "geeks quiz practice code"
printRev(strr)
# This code is contributed by mohit kumar 29
C#
// C# program to implement
// the above approach
using System;
using System.Collections;
class GFG{
// Function to reverse the words
// of a given String
static void printRev(string str)
{
// Stack to store each
// word of the String
Stack st = new Stack();
String[] separator = {" "};
// Store the whole String
// in String stream
string[] ss = str.Split(separator,
int.MaxValue,
StringSplitOptions.RemoveEmptyEntries);
foreach(string temp in ss)
{
// Push each word of the
// String into the stack
st.Push(temp);
}
// Print the String in reverse
// order of the words
while (st.Count > 0)
{
Console.Write(st.Peek() + " ");
st.Pop();
}
}
// Driver Code
public static void Main(string[] args)
{
string str;
str = "geeks quiz practice code";
printRev(str);
}
}
// This code is contributed by rutvik_56
JavaScript
<script>
// Javascript Program to implement
// the above approach
// Function to reverse the words
// of a given String
function printRev(str)
{
// Stack to store each
// word of the String
let st = [];
// Store the whole String
// in String stream
let ss = str.split(" ");
for (let temp=0;temp< ss.length;temp++)
{
// Push each word of the
// String into the stack
st.push(ss[temp]);
}
// Print the String in reverse
// order of the words
while (st.length!=0)
{
document.write(st.pop() + " ");
}
}
// Driver Code
let str;
str = "geeks quiz practice code";
printRev(str);
// This code is contributed by unknown2108
</script>
Outputcode practice quiz geeks
Time Complexity: O(N), where N denotes the length of the string.
Auxiliary Space: O(N)
Method #2: Using built-in python functions
- As all the words in a sentence are separated by spaces.
- We have to split the sentence by spaces using split().
- We split all the words by spaces and store them in a list.
- Reverse this list and print it.
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to reverse the words
// of a given string
void printRev(string lis[])
{
// reverse the list
reverse(lis, lis + 4);
for(int i = 0; i < 4; i++)
{
cout << lis[i] << " ";
}
}
int main()
{
string strr[] = {"geeks", "quiz", "practice", "code"};
printRev(strr);
return 0;
}
// This code is contributed by divyeshrabadiya07.
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
// Function to reverse the words
// of a given string
static void printRev(String string)
{
// Split by space and converting
// string to list
String[] lis = string.split(" ", 0);
// Reverse the list
Collections.reverse(Arrays.asList(lis));
// Printing the list
for(String li : lis)
{
System.out.print(li + " ");
}
}
// Driver code
public static void main(String[] args)
{
String strr = "geeks quiz practice code";
printRev(strr);
}
}
// This code is contributed by decode2207
Python3
# Python3 program to implement
# the above approach
# Function to reverse the words
# of a given string
def printRev(string):
# split by space and converting
# string to list
lis = list(string.split())
# reverse the list
lis.reverse()
# printing the list
print(*lis)
# Driver Code
if __name__ == '__main__':
strr = "geeks quiz practice code"
printRev(strr)
# This code is contributed by vikkycirus
C#
// C# program to implement
// the above approach
using System;
class GFG {
// Function to reverse the words
// of a given string
static void printRev(string String)
{
// split by space and converting
// string to list
string[] lis = String.Split(' ');
// reverse the list
Array.Reverse(lis);
// printing the list
foreach(string li in lis)
{
Console.Write(li + " ");
}
}
static void Main() {
string strr = "geeks quiz practice code";
printRev(strr);
}
}
// This code is contributed by rameshtravel07.
JavaScript
<script>
// javascript program to implement
// the above approach
// Function to reverse the words
// of a given string
function printRev(string){
// split by space and converting
// string to list
var lis = string.split(' ');
console.log(lis);
// reverse the list
lis.reverse();
console.log(lis);
// printing the list
document.write(lis.join(' '));
}
// Driver Code
var strr = "geeks quiz practice code"
printRev(strr)
</script>
Outputcode practice quiz geeks
Time Complexity : O(n), n is the number of strings.
Auxiliary Space : O(1)
Using a loop and stack in python:
Approach:
The function starts by importing the time module, which is used to measure the time taken to perform the operation.
The function defines a variable stack as an empty list, which will be used to store the words in reverse order.
The function also defines a variable word as an empty string, which will be used to store each word in the input string as it is being read.
The function then iterates over each character c in the input string s.
If the character is a space, the word variable is appended to the stack list, and the word variable is reset to an empty string to start building the next word.
If the character is not a space, it is added to the current word being built.
After all characters have been processed, the last word variable is appended to the stack list.
The function then defines a variable result as an empty string, which will be used to store the reversed string.
The function then enters a loop that pops words from the stack list in reverse order, concatenates them with a space, and adds the resulting string to the result variable.
The loop continues until all words have been popped from the stack list.
The resulting string in result is stripped of any trailing spaces and returned along with the time taken to perform the operation.
Finally, the function is called twice with two different input strings (s1 and s2) to demonstrate how the function works.
Python3
import time
def reverse_words(s):
start_time = time.time()
stack = []
word = ""
for c in s:
if c == " ":
stack.append(word)
word = ""
else:
word += c
stack.append(word)
result = ""
while stack:
result += stack.pop() + " "
result = result.strip()
end_time = time.time()
return result, end_time - start_time
# example usage
s1 = "geeks quiz practice code"
s2 = "getting good at coding needs a lot of practice"
result, time_taken = reverse_words(s1)
print(result)
print(f"Time taken: {time_taken} seconds")
result, time_taken = reverse_words(s2)
print(result)
print(f"Time taken: {time_taken} seconds")
Outputcode practice quiz geeks
Time taken: 1.049041748046875e-05 seconds
practice of lot a needs coding at good getting
Time taken: 6.9141387939453125e-06 seconds
Time complexity: O(n), where n is the length of the input string. This is because we iterate over each character in the string once, which takes O(n) time. We also append each word to a stack, which takes O(1) time per operation.
Space complexity: O(n), where n is the length of the input string. This is because we create a stack to store the words, which can take up to O(n) space in the worst case.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem