Introduction
The Reverse String problem involves reversing the order of characters in a string.
Given a string s, the task is to:
- reverse all characters
- return the reversed string
This problem helps in understanding:
- string traversal
- swapping techniques
- Two Pointer Technique
- in-place modification
Example
Input:s = "hello"
Output:
"olleh"
Explanation:
Characters are reversed from end to beginning.
Input: s = "coding"
Output:
"gnidoc"
Explanation:
First character becomes last
and last character becomes first.
Constraints
1 <= s.length <= 10^5s contains printable ASCII characters
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Traverse the string from end
- Append characters into a new string
This approach is easy to understand but uses extra space.
Steps
- Create empty result string.
- Traverse original string from end.
- Append characters into result.
- Return reversed string.
Dry Run
Input:s = "hello"
Traverse from end:
o → result = "o"
l → result = "ol"
l → result = "oll"
e → result = "olle"
h → result = "olleh"
Final Result:
"olleh"
Brute Force Code
Complexity Analysis
Time Complexity: O(n)Explanation:
Each character is traversed once.
Space Complexity: O(n)
Explanation:
Extra result string is used.
Approach 2 : Optimized Solution (Two Pointer Technique)
Explanation
The optimized solution uses the Two Pointer Technique.
The idea is:
- Place:
- left pointer at beginning
- right pointer at end
- Swap characters.
- Move pointers toward center.
This reverses the string efficiently.
Steps
- Convert string into character array.
- Initialize:
- left = 0
- right = n - 1
- Swap characters.
- Move pointers inward.
- Return reversed string.
Dry Run
Input:s = "hello"
Initially:
left = 0 → h
right = 4 → o
Swap:
o e l l h
Move pointers
left = 1 → e
right = 3 → l
Swap:
o l l e h
Pointers cross
Final Result:
"olleh"
Optimized Code
Complexity Analysis
Time Complexity: O(n)Explanation: Each character is processed once.
Space Complexity: O(n)
Explanation: Reversal is performed in-place.