Start learning free

LESSON 245 OF 410 · TWO POINTERS

Reverse String in O(n) Time and O(n) Space using Python

Practice O(n) Read the full explanation

Given a string, write a function that reverses that string without using built-in functions or libraries.

Example:

Input:  "hello"

Output: "olleh"

Note:

Your algorithm should run in O(n) time and use O(n) extra space.


STEP 1 OF 9
    Ctrl + Enter to check

    PYTHON · TWO POINTERS

    Reverse String in Python, explained

    Understanding the Problem

    The core challenge of this problem is to reverse a given string without using any built-in functions or libraries. This means we need to manually manipulate the string to achieve the desired result.

    Reversing a string is a common problem in computer science with applications in data processing, text manipulation, and algorithms that require reversing sequences.

    Potential pitfalls include misunderstanding the constraints (e.g., not using extra space or built-in functions) and handling edge cases like empty strings or single-character strings.

    Approach

    To solve this problem, we can use a few different approaches:

    Naive Solution

    A naive solution might involve iterating through the string from the end to the beginning and constructing a new string. However, this approach is not optimal because it may involve multiple string concatenations, which can be inefficient.

    Optimized Solution

    An optimized solution involves using a list to store the characters of the string in reverse order and then converting the list back to a string. This approach ensures that we only traverse the string once, achieving O(n) time complexity, and we use O(n) extra space for the list.

    Algorithm

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

    1. Initialize an empty list to store the characters of the reversed string.
    2. Iterate through the original string from the end to the beginning.
    3. Append each character to the list.
    4. Join the list into a single string and return it.

    Code Implementation

    def reverse_string(s):
        # Initialize an empty list to store the reversed characters
        reversed_chars = []
        
        # Iterate through the string from the end to the beginning
        for i in range(len(s) - 1, -1, -1):
            reversed_chars.append(s[i])
        
        # Join the list into a single string and return it
        return ''.join(reversed_chars)
    
    # Example usage
    input_string = "hello"
    output_string = reverse_string(input_string)
    print(output_string)  # Output: "olleh"
    

    Complexity Analysis

    The time complexity of this algorithm is O(n) because we iterate through the string once. The space complexity is also O(n) because we use a list to store the reversed characters.

    Compared to the naive approach, this solution is more efficient because it avoids multiple string concatenations.

    Edge Cases

    Let's consider some edge cases:

    • Empty string: The function should return an empty string.
    • Single-character string: The function should return the same string.
    • String with spaces: The function should correctly reverse the string, including spaces.

    Examples:

    reverse_string("")  # Output: ""
    reverse_string("a")  # Output: "a"
    reverse_string("a b c")  # Output: "c b a"
    

    Testing

    To test the solution comprehensively, we should include a variety of test cases:

    • Simple strings
    • Strings with spaces
    • Empty strings
    • Single-character strings

    Example test cases:

    def test_reverse_string():
        assert reverse_string("hello") == "olleh"
        assert reverse_string("") == ""
        assert reverse_string("a") == "a"
        assert reverse_string("a b c") == "c b a"
        assert reverse_string("12345") == "54321"
        print("All test cases pass")
    
    test_reverse_string()
    

    Thinking and Problem-Solving Tips

    When approaching such problems, it's important to:

    • Understand the constraints and requirements.
    • Think about different approaches and their trade-offs.
    • Break down the problem into smaller, manageable steps.
    • Test your solution with various edge cases.

    To improve problem-solving skills, practice solving similar problems and study different algorithms and data structures.

    Conclusion

    In this blog post, we discussed how to reverse a string in O(n) time and O(n) space using Python. We explored different approaches, provided a detailed algorithm, and implemented the solution with comprehensive testing. Understanding and solving such problems is crucial for developing strong problem-solving skills in computer science.

    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