Reverse Words in a String LeetCode Programming Solutions | LeetCode Problem Solutions in C++, Java, & Python [💯Correct]

LeetCode Problem | LeetCode Problems For Beginners | LeetCode Problems & Solutions | Improve Problem Solving Skills | LeetCode Problems Java | LeetCode Solutions in C++

Hello Programmers/Coders, Today we are going to share solutions to the Programming problems of LeetCode Solutions in C++, Java, & Python. At Each Problem with Successful submission with all Test Cases Passed, you will get a score or marks and LeetCode Coins. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.

In this post, you will find the solution for the Reverse Words in a String in C++, Java & Python-LeetCode problem. We are providing the correct and tested solutions to coding problems present on LeetCode. If you are not able to solve any problem, then you can take help from our Blog/website.

Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.

About LeetCode

LeetCode is one of the most well-known online judge platforms to help you enhance your skills, expand your knowledge and prepare for technical interviews. 

LeetCode is for software engineers who are looking to practice technical questions and advance their skills. Mastering the questions in each level on LeetCode is a good way to prepare for technical interviews and keep your skills sharp. They also have a repository of solutions with the reasoning behind each step.

LeetCode has over 1,900 questions for you to practice, covering many different programming concepts. Every coding problem has a classification of either EasyMedium, or Hard.

LeetCode problems focus on algorithms and data structures. Here is some topic you can find problems on LeetCode:

  • Mathematics/Basic Logical Based Questions
  • Arrays
  • Strings
  • Hash Table
  • Dynamic Programming
  • Stack & Queue
  • Trees & Graphs
  • Greedy Algorithms
  • Breadth-First Search
  • Depth-First Search
  • Sorting & Searching
  • BST (Binary Search Tree)
  • Database
  • Linked List
  • Recursion, etc.

Leetcode has a huge number of test cases and questions from interviews too like Google, Amazon, Microsoft, Facebook, Adobe, Oracle, Linkedin, Goldman Sachs, etc. LeetCode helps you in getting a job in Top MNCs. To crack FAANG Companies, LeetCode problems can help you in building your logic.

Link for the ProblemReverse Words in a String– LeetCode Problem

Reverse Words in a String– LeetCode Problem


Given an input string s, reverse the order of the words.

word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Example 1:

Input: s = "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: s = "  hello world  "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: s = "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.


  • 1 <= s.length <= 104
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • There is at least one word in s.
Reverse Words in a String– LeetCode Solutions
Reverse Words in a String Solution in C++:
class Solution {
  string reverseWords(string s) {
    reverse(begin(s), end(s));          // reverse the whole string
    reverseWords(s, s.length());        // reverse each word
    return cleanSpaces(s, s.length());  // clean up spaces

  void reverseWords(string& s, int n) {
    int i = 0;
    int j = 0;

    while (i < n) {
      while (i < j || i < n && s[i] == ' ')  // skip spaces
      while (j < i || j < n && s[j] != ' ')  // skip non spaces
      reverse(begin(s) + i, begin(s) + j);  // reverse the word

  // trim leading, trailing, and middle spaces
  string cleanSpaces(string& s, int n) {
    int i = 0;
    int j = 0;

    while (j < n) {
      while (j < n && s[j] == ' ')  // skip spaces
      while (j < n && s[j] != ' ')  // keep non spaces
        s[i++] = s[j++];
      while (j < n && s[j] == ' ')  // skip spaces
      if (j < n)  // keep only one space
        s[i++] = ' ';

    return s.substr(0, i);
Reverse Words in a String Solution in Java:
class Solution {
  public String reverseWords(String s) {
    StringBuilder sb = new StringBuilder(s).reverse(); // reverse the whole string
    reverseWords(sb, sb.length());                     // reverse each word
    return cleanSpaces(sb, sb.length());               // clean up spaces

  private void reverseWords(StringBuilder sb, int n) {
    int i = 0;
    int j = 0;

    while (i < n) {
      while (i < j || i < n && sb.charAt(i) == ' ') // skip spaces
      while (j < i || j < n && sb.charAt(j) != ' ') // skip non spaces
      reverse(sb, i, j - 1); // reverse the word

  // trim leading, trailing, and middle spaces
  private String cleanSpaces(StringBuilder sb, int n) {
    int i = 0;
    int j = 0;

    while (j < n) {
      while (j < n && sb.charAt(j) == ' ') // skip spaces
      while (j < n && sb.charAt(j) != ' ') // keep non spaces
        sb.setCharAt(i++, sb.charAt(j++));
      while (j < n && sb.charAt(j) == ' ') // skip spaces
      if (j < n) // keep only one space
        sb.setCharAt(i++, ' ');

    return sb.substring(0, i).toString();

  private void reverse(StringBuilder sb, int l, int r) {
    while (l < r) {
      final char temp = sb.charAt(l);
      sb.setCharAt(l++, sb.charAt(r));
      sb.setCharAt(r--, temp);
Reverse Words in a String Solution in Python:
class Solution:
  def reverseWords(self, s: str) -> str:
    return ' '.join(reversed(s.split()))

Leave a Comment

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock