Problem 344: Reverse String
Question
LeetCode Link | 344. Reverse String | Easy
Write a function that reverses a string. The input string is given as an array of characters s
.
You must do this by modifying the input array in-place with O(1)
extra memory.
Constrains
1 <= s.length <= 10^5
s[i]
is a printable ascii character.
Examples
Example 1
Input: s = [“h”,”e”,”l”,”l”,”o”]
Output: [“o”,”l”,”l”,”e”,”h”]
Example 2
Input: s = [“H”,”a”,”n”,”n”,”a”,”h”]
Output: [“h”,”a”,”n”,”n”,”a”,”H”]
Solution Approach
Method: Two-pointers
Constrains
- None
This method does not have any limitations.
Concept Explanation
To modifying the input array in place, we need swap two string while iterating the array. Two pointer method will perfectly fit this one.
We define two pointers or saying the index of that array. One pointer locate at the start of the array, another pointer at the end of the array. Swapping the string on these two indexes, and then move these two pointers into center direction, reverse is complete when they meet in center.
Code
- Time complexity: O(n)
- Space complexity: O(1)
TypeScript
1 | /** |
Conclusion
This problem could be done by calling built-in function reverse()
. However, If the key part of a problem can be directly solved using a library function, it is advisable not to use the library function. If the library function is only a small part of the solution process and you are well aware of how the function is implemented internally, then you may consider using the library function.