Reverse Words in a String in Data Structures

Learn via video course
FREE
View all courses
DSA Problem Solving for Interviews using Java
DSA Problem Solving for Interviews using Java
by Jitender Punia
1000
4.9
Start Learning
DSA Problem Solving for Interviews using Java
DSA Problem Solving for Interviews using Java
by Jitender Punia
1000
4.9
Start Learning
Topics Covered

Overview

In this problem "Reverse words in a String", we are given an input string s. We need to reverse the order of the words and return a string of the words in reverse order.

Takeaways

In this article we will learn how to reverse words in a string using different approach.

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

Example

Input :

Output :

Example Explanation

The string given to us is "welcome to scaler topics". To reverse the words of this string, we need to think of a logic to reverse the words and also to remove any leading or trailing spaces. This gives us "topics scaler to welcome".

Constraints

  • Length of the string s will be between 1 and 104.
  • s could contain English letters (upper-case and lower-case), digits, and spaces ' '.
  • There is at least one word in s.
Free Courses by top Scaler instructors
Python Course for Beginners With Certification: Mastering the Essentials
Java Course - Mastering the Fundamentals
DBMS Course - Master the Fundamentals and Advanced Concepts
JavaScript Course With Certification: Unlocking the Power of JavaScript
C++ Course: Learn the Essentials
Python and SQL for Data Science
Python Course for Beginners With Certification: Mastering the Essentials
Java Course - Mastering the Fundamentals
DBMS Course - Master the Fundamentals and Advanced Concepts
JavaScript Course With Certification: Unlocking the Power of JavaScript
C++ Course: Learn the Essentials
Python and SQL for Data Science

Approach 1 : Splitting and Saving the String in a Reverse Manner

One of the easiest ways to reverse words in a string is by splitting the string and then saving it in reverse order. This is the naive approach. We will now look at the code for this method :

Java Implementation

In Java, we have the split method, which helps us split the string. We use it to split the string using the delimiter and reverse and store the line in another variable.

Output :

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more

Python Implementation

In python too, we have the split method, which helps us split the string. We use it to split the string using the delimiter and reverse and store the line in another variable.

Output :

C++ Implementation

Output :

Complexity Analysis

Let's analyze the time and space complexity of this approach :

Time Complexity : O(n)O(n) as we use only one for a loop.
Space Complexity : O(n)O(n) as we are storing our output that is, the reversed string in a new variable.

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

Approach 2 : Using the Two-Pointers Approach

Now, here comes the optimal solution for this problem.

We initialize two pointers, one at the start of the string and another at the end. Then, we swap the words from the start and end, to achieve the reversed string.

Algorithm :

  1. Turn the string s into an array of strings in which the words of s are stored.
  2. Now, initialise the left and right pointers at 0 and s.length()s.length()11.
  3. Now, we need to swap the elements at the left and right pointers. For that, move the left pointer ahead and the right pointer backward by one position and swap the elements at each position while the left pointer does not exceed the right pointer.
  4. Return the final string.

Java Implementation

Output :

Python Implementation

Output :

C++ Implementation

Output :

Complexity Analysis

Let's analyze the time and space complexity of this approach :

Time Complexity : O(n)O(n)
Space Complexity : O(1)O(1)

Conclusion

  • Reverse words in a string is a really important problem regarding interview preparation.
  • One of the easiest ways to solve this problem is by splitting the string and then saving it in reverse order.
  • Another way is to swap the words from the start and end to achieve the reversed string. This is also the optimal solution to the problem.