Reverse String - Problem
The Challenge: You're given a string as an array of characters and need to reverse it in-place. This means you must modify the original array without creating a new one, using only
What you get: An array of characters like
What you return: The same array, but reversed:
This is a fundamental string manipulation problem that tests your understanding of array indexing and space-efficient algorithms. The constraint of in-place modification makes it more challenging than simply creating a new reversed string.
O(1) extra memory space.What you get: An array of characters like
['h','e','l','l','o']What you return: The same array, but reversed:
['o','l','l','e','h']This is a fundamental string manipulation problem that tests your understanding of array indexing and space-efficient algorithms. The constraint of in-place modification makes it more challenging than simply creating a new reversed string.
Input & Output
example_1.py โ Basic String
$
Input:
s = ['h','e','l','l','o']
โบ
Output:
['o','l','l','e','h']
๐ก Note:
We reverse the string 'hello' by swapping characters from both ends moving inward. First swap hโo, then eโl, leaving the middle 'l' unchanged.
example_2.py โ Even Length
$
Input:
s = ['H','a','n','n','a','h']
โบ
Output:
['h','a','n','n','a','H']
๐ก Note:
For even-length strings, we swap all pairs: Hโh, aโa, nโn. Each character finds its mirror position.
example_3.py โ Single Character
$
Input:
s = ['A']
โบ
Output:
['A']
๐ก Note:
Edge case: A single character string remains unchanged since there are no other characters to swap with.
Constraints
- 1 โค s.length โค 105
- s[i] is a printable ASCII character
- Must modify the input array in-place with O(1) extra memory
Visualization
Tap to expand
Understanding the Visualization
1
Place Pointers
Position left pointer at start (index 0) and right pointer at end (index n-1)
2
Swap & Move
Swap characters at pointer positions, then move left pointer right and right pointer left
3
Meet in Middle
Continue until pointers meet or cross - the string is now reversed!
Key Takeaway
๐ฏ Key Insight: By using two pointers that converge toward the center, we can reverse any string in-place with optimal space efficiency, requiring only constant extra memory regardless of input size.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code