Start learning free

LESSON 248 OF 410 · TWO POINTERS

Reverse Words in a String II - Python Solution with O(n) Time Complexity

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 14
    Ctrl + Enter to check

    PYTHON · TWO POINTERS

    Reverse Words in Python, 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 manipulation, which is a common task in software development, especially in natural language processing (NLP).

    Potential pitfalls include misunderstanding the definition of a word and mishandling multiple spaces, but the problem simplifies this by ensuring words are separated by a single space.

    Approach

    To solve this problem, we can follow these steps:

    1. Split the input string into words.
    2. Reverse the list of words.
    3. Join the reversed list of words back into a single string with spaces in between.

    Let's discuss a naive solution and then an optimized solution:

    Naive Solution

    The naive solution involves manually iterating through the string to identify words, storing them in a list, and then reversing the list. This approach is not optimal due to the manual handling of string operations.

    Optimized Solution

    The optimized solution leverages Python's built-in string and list operations, which are highly efficient. By using the split() method, we can easily break the string into words, and the join() method allows us to concatenate them back together.

    Algorithm

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

    1. Use the split() method to split the input string into a list of words.
    2. Reverse the list of words using slicing or the reverse() method.
    3. Use the join() method to concatenate the reversed list into a single string with spaces in between.

    Code Implementation

    def reverse_words(s: str) -> str:
        # Split the string into words
        words = s.split()
        # Reverse the list of words
        words.reverse()
        # Join the reversed list into a single string with spaces
        return ' '.join(words)
    
    # Example usage
    input_string = "sky is blue"
    output_string = reverse_words(input_string)
    print(output_string)  # Output: "blue is sky"
    

    Complexity Analysis

    The time complexity of this solution is O(n), where n is the length of the input string. This is because splitting the string and joining the words both take linear time. The space complexity is also O(n) due to the storage of the list of words.

    Edge Cases

    Consider the following edge cases:

    • Empty string: The output should also be an empty string.
    • String with one word: The output should be the same as the input.
    • String with multiple spaces: The problem guarantees single spaces between words, so this is not a concern.

    Examples:

    reverse_words("")  # Output: ""
    reverse_words("hello")  # Output: "hello"
    reverse_words("hello world")  # Output: "world hello"
    

    Testing

    To test the solution comprehensively, consider a variety of test cases:

    • Simple cases with a few words.
    • Edge cases like empty strings and single words.
    • Long strings to ensure performance.

    Using a testing framework like unittest in Python can help automate and organize these tests.

    Thinking and Problem-Solving Tips

    When approaching such problems, it's essential to:

    • Understand the problem requirements and constraints thoroughly.
    • Break down the problem into smaller, manageable parts.
    • Consider both naive and optimized solutions to understand different approaches.
    • Practice similar problems to improve problem-solving skills.

    Conclusion

    Reversing the words in a string is a common problem that helps in understanding string manipulation and list operations. By practicing such problems, you can improve your problem-solving skills and prepare for more complex challenges.

    Additional Resources

    For further reading and practice, consider the following resources:

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