What is Reverse String?
Reverse String is a basic string manipulation algorithm that reverses the order of characters in a string. The most efficient approach uses two pointers—one starting from the beginning and the other from the end—and swaps characters until both pointers meet.
Example
- Input String: HELLO
- Left points to H
- Right points to O
- Swap H and O → OELLH
- Move pointers inward
- Swap E and L → OLLEH
- Pointers meet → Finished
This approach performs the reversal in-place without using any additional array, making it both time and space efficient.
Algorithm Steps
- Initialize Left pointer at index 0.
- Initialize Right pointer at the last index.
- Swap characters at Left and Right.
- Increment Left pointer.
- Decrement Right pointer.
- Repeat until Left ≥ Right.
Complexity Analysis
- Best Case: O(n)
- Average Case: O(n)
- Worst Case: O(n)
- Space Complexity: O(1)
Time Complexity Analysis
Reverse String is frequently used in interviews and serves as a foundation for many advanced string algorithms such as palindrome checking and rotation problems.