Start learning free

LESSON 194 OF 409 · STRINGS

Reverse String III in C++ with O(n) Time Complexity

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

    C++ · STRINGS

    Reverse String in C++, 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 more. A common pitfall is to overlook the constraints, such as not using built-in functions, which can lead to incorrect solutions.

    Approach

    To solve this problem, we can use a two-pointer technique. This approach involves swapping characters from the beginning and end of the string, moving towards the center. This method ensures that we reverse the string in-place, achieving O(n) time complexity.

    Let's break down the approach:

    1. Initialize two pointers: one at the start of the string and one at the end.
    2. Swap the characters at these pointers.
    3. Move the pointers towards the center.
    4. Repeat the process until the pointers meet or cross each other.

    Algorithm

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

    1. Initialize two pointers, left at the start (0) and right at the end (n-1) of the string.
    2. While left is less than right:
      • Swap the characters at left and right.
      • Increment left and decrement right.
    3. Return the modified string.

    Code Implementation

    
    #include <iostream>
    #include <string>
    
    // Function to reverse a string
    std::string reverseString(const std::string &input) {
        // Create a mutable copy of the input string
        std::string str = input;
        int left = 0;
        int right = str.length() - 1;
    
        // Use two-pointer technique to reverse the string
        while (left < right) {
            // Swap characters at left and right pointers
            char temp = str[left];
            str[left] = str[right];
            str[right] = temp;
    
            // Move pointers towards the center
            left++;
            right--;
        }
    
        return str;
    }
    
    int main() {
        std::string input = "hello";
        std::string output = reverseString(input);
        std::cout << "Reversed string: " << output << std::endl;
        return 0;
    }
    

    Complexity Analysis

    The time complexity of this approach is O(n), where n is the length of the string. This is because we are iterating through the string once, swapping characters. The space complexity is also O(n) due to the mutable copy of the input string.

    Edge Cases

    Consider the following edge cases:

    • Empty string: The function should return an empty string.
    • Single character string: The function should return the same string.
    • Strings with special characters and spaces: The function should correctly reverse the entire string, including special characters and spaces.

    Examples:

    Input: ""
    Output: ""
    
    Input: "a"
    Output: "a"
    
    Input: "a b c"
    Output: "c b a"
    

    Testing

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

    • Simple strings: "hello", "world"
    • Strings with spaces: "a b c", "hello world"
    • Strings with special characters: "a!b@c#", "123!@#"
    • Edge cases: "", "a"

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

    Thinking and Problem-Solving Tips

    When approaching such problems, consider the following tips:

    • Understand the constraints and requirements thoroughly.
    • Break down the problem into smaller, manageable parts.
    • Think about different approaches and their trade-offs.
    • Practice similar problems to improve problem-solving skills.

    Conclusion

    Reversing a string is a fundamental problem that helps in understanding string manipulation and algorithm design. By practicing and exploring different approaches, you can enhance your problem-solving skills and apply them to more complex problems.

    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