Start learning free

LESSON 247 OF 409 · TWO POINTERS

Reverse Words in a String II - C++ Solution and Time Complexity Analysis

Practice O(n) Read the full explanation

Given a string input, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in input will be separated by one space for simplicity.

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

Example:

Input:  input = "sky is blue"

Output:  "blue is sky"
STEP 1 OF 13
    Ctrl + Enter to check

    C++ · TWO POINTERS

    Reverse Words in C++, explained

    Understanding the Problem

    The core challenge of this problem is to reverse the order of words in a given string while maintaining the integrity of each word. This problem is significant in text processing and has applications in natural language processing, data formatting, and more.

    Potential pitfalls include handling multiple spaces, leading or trailing spaces, and ensuring that the words are correctly identified and reversed.

    Approach

    To solve this problem, we can consider the following approaches:

    Naive Solution

    A naive solution would involve splitting the string into words, reversing the list of words, and then joining them back into a single string. This approach, while straightforward, may not be the most efficient in terms of space complexity.

    Optimized Solution

    An optimized solution would involve reversing the entire string first and then reversing each word in place. This approach minimizes the use of extra space and is more efficient.

    Algorithm

    Here is a step-by-step breakdown of the optimized algorithm:

    1. Reverse the entire string.
    2. Iterate through the reversed string and reverse each word in place.
    3. Return the modified string.

    Code Implementation

    
    #include <iostream>
    #include <string>
    #include <algorithm>
    
    using namespace std;
    
    // Function to reverse words in a string
    string reverseWords(string s) {
        // Reverse the entire string
        reverse(s.begin(), s.end());
        
        int start = 0, end = 0, n = s.length();
        
        while (end < n) {
            // Find the end of the current word
            while (end < n && s[end] != ' ') {
                end++;
            }
            
            // Reverse the current word
            reverse(s.begin() + start, s.begin() + end);
            
            // Move to the next word
            start = end + 1;
            end++;
        }
        
        return s;
    }
    
    int main() {
        string input = "sky is blue";
        string output = reverseWords(input);
        cout << "Output: " << output << endl;
        return 0;
    }
    

    Complexity Analysis

    The time complexity of the optimized solution is O(n), where n is the length of the string. This is because we are performing a constant amount of work for each character in the string.

    The space complexity is O(1) as we are modifying the string in place and not using any extra space proportional to the input size.

    Edge Cases

    Potential edge cases include:

    • Empty string: The function should return an empty string.
    • String with multiple spaces: The function should handle multiple spaces correctly.
    • String with leading or trailing spaces: The function should trim the spaces appropriately.

    Testing

    To test the solution comprehensively, consider the following test cases:

    • Input: "sky is blue" - Output: "blue is sky"
    • Input: " hello world " - Output: "world hello"
    • Input: "a good example" - Output: "example good a"
    • Input: "" - Output: ""

    Using a testing framework like Google Test can help automate and validate these test cases.

    Thinking and Problem-Solving Tips

    When approaching such problems, it is essential to:

    • Understand the problem requirements and constraints thoroughly.
    • Break down the problem into smaller, manageable parts.
    • Consider edge cases and how to handle them.
    • Optimize the solution by minimizing time and space complexity.

    Practicing similar problems and studying various algorithms can significantly improve problem-solving skills.

    Conclusion

    Reversing words in a string is a common problem in text processing. Understanding and implementing an optimized solution can enhance your coding skills and prepare you for more complex challenges. Keep practicing and exploring different approaches to improve your problem-solving abilities.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free