Reverse String
LeetCode Problem #344 (Easy)
Problem Statement
Write a function that reverses a string. The input string is given as an array of characters char[]
.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ASCII characters.
Testcases
Prerequisite Knowledge
Swapping using a Temporary Variable
To swap elements in place, we can make use of a temporary variable.
Algorithm
Swap Characters Approach
In this approach, we simply swap the characters from either end of the character array which would ultimately produce a reversed version of the original array.
Calculate the length of the array and store it in a variable.
Initialize two pointers to point to the extreme ends of the array.
Traverse the array and swap the elements at the left and right positions, using a temporary variable.
When the left and right pointers become equal or break the condition (left < right), stop.
Code
Last updated
Was this helpful?