Start learning free

LESSON 245 OF 410 · TWO POINTERS

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

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

    JAVASCRIPT · TWO POINTERS

    Reverse String in JavaScript, explained

    Problem Definition

    In this problem, we are required to reverse a given string without using any built-in functions or libraries. The input is a single string, and the output should be the reversed version of that string.

    Input:

    • A single string s.

    Output:

    • A single string which is the reverse of s.

    Constraints:

    • The algorithm should run in O(n) time complexity.
    • The algorithm should use O(n) extra space.

    Example:

    Input: "hello"
    Output: "olleh"

    Understanding the Problem

    The core challenge of this problem is to reverse the string efficiently without using any built-in functions. This is a common problem in computer science with applications in data processing, text manipulation, and more. A potential pitfall is to use built-in functions like reverse() which is not allowed in this problem.

    Approach

    To solve this problem, we need to think about how to reverse a string manually. A naive solution might involve iterating through the string and constructing the reversed string character by character. However, this approach needs to be optimized to meet the constraints.

    Naive Solution

    A naive solution would involve iterating through the string from the end to the beginning and appending each character to a new string. This approach is straightforward but not optimal in terms of space complexity.

    Optimized Solution

    An optimized solution involves using an array to store the characters of the string in reverse order. This approach ensures that we only traverse the string once (O(n) time complexity) and use an array of the same length as the string (O(n) space complexity).

    Algorithm

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

    1. Initialize an empty array to store the reversed characters.
    2. Iterate through the string from the end to the beginning.
    3. For each character, append it to the array.
    4. Join the array into a single string and return it.

    Code Implementation

    // Function to reverse a string
    function reverseString(s) {
        // Initialize an empty array to store the reversed characters
        let reversedArray = [];
        
        // Iterate through the string from the end to the beginning
        for (let i = s.length - 1; i >= 0; i--) {
            // Append each character to the array
            reversedArray.push(s[i]);
        }
        
        // Join the array into a single string and return it
        return reversedArray.join('');
    }
    
    // Example usage
    console.log(reverseString("hello")); // 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 an array to store the reversed characters.

    Edge Cases

    Potential edge cases include:

    • An empty string: The function should return an empty string.
    • A single character string: The function should return the same character.
    • Strings with spaces and special characters: The function should handle these correctly.

    Examples of Edge Cases:

    Input: ""
    Output: ""
    
    Input: "a"
    Output: "a"
    
    Input: "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
    • Strings with special characters
    • Empty strings
    • Single character strings

    Example Test Cases:

    console.log(reverseString("hello")); // Output: "olleh"
    console.log(reverseString("a b c")); // Output: "c b a"
    console.log(reverseString("")); // Output: ""
    console.log(reverseString("a")); // Output: "a"
    console.log(reverseString("12345")); // Output: "54321"
    

    Thinking and Problem-Solving Tips

    When approaching such problems, it's important to:

    • Understand the problem requirements and constraints.
    • Think about different ways to solve the problem and their trade-offs.
    • Start with a simple solution and then optimize it.
    • Practice similar problems to improve problem-solving skills.

    Conclusion

    Reversing a string is a fundamental problem that helps in understanding basic string manipulation techniques. By solving this problem, we learn how to think about string operations and optimize our solutions to meet specific constraints.

    Additional Resources

    For further reading and practice, consider the following resources:

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