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


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.


Problem Definition

The task is 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:

Output:

Constraints:

Example:

Input: "hello"
Output: "olleh"

Understanding the Problem

The core challenge is to reverse the string efficiently without using any built-in functions. This problem is significant as it tests the understanding of string manipulation and memory usage. Common applications include data processing and manipulation tasks where reversing strings is a fundamental operation.

Potential pitfalls include misunderstanding the constraints and attempting to use built-in functions, which is not allowed.

Approach

To solve this problem, we need to think about how to reverse a string manually. A naive solution might involve swapping characters from the start and end of the string until the middle is reached. However, since we cannot use built-in functions, we need to handle the string as an array of characters.

Naive Solution

A naive approach would be to create a new string and append characters from the end of the original string to the beginning of the new string. This approach is not optimal because it involves multiple string concatenations, which are costly in terms of time complexity.

Optimized Solution

An optimized solution involves using a character array to store the reversed string. We can iterate over the original string from the end to the beginning and fill the character array. This approach ensures O(n) time complexity and O(n) space complexity.

Algorithm

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

  1. Create a character array of the same length as the input string.
  2. Iterate over the input string from the end to the beginning.
  3. For each character in the input string, place it in the corresponding position in the character array.
  4. Convert the character array back to a string and return it.

Code Implementation

public class ReverseString {
    public static String reverse(String s) {
        // Create a character array to hold the reversed string
        char[] reversed = new char[s.length()];
        
        // Iterate over the input string from the end to the beginning
        for (int i = 0; i < s.length(); i++) {
            // Place each character in the corresponding position in the reversed array
            reversed[i] = s.charAt(s.length() - 1 - i);
        }
        
        // Convert the character array back to a string and return it
        return new String(reversed);
    }

    public static void main(String[] args) {
        // Test the reverse function
        String input = "hello";
        String output = reverse(input);
        System.out.println("Reversed string: " + output); // Expected output: "olleh"
    }
}

Complexity Analysis

The time complexity of this approach is O(n) because we iterate over the string once. The space complexity is also O(n) because we use an additional character array to store the reversed string.

Edge Cases

Potential edge cases include:

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:

Use a testing framework like JUnit to automate the testing process.

Thinking and Problem-Solving Tips

When approaching such problems, break down the task into smaller steps and think about how to manipulate the data manually. Practice similar problems to develop problem-solving skills and understand different algorithms and their trade-offs.

Conclusion

Reversing a string is a fundamental problem that helps in understanding string manipulation and memory usage. By practicing such problems, you can improve your problem-solving skills and prepare for more complex challenges.

Additional Resources