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

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.

Reverse String

Code

  • Time complexity: O(n)
  • Space complexity: O(1)

TypeScript

1
2
3
4
5
6
7
8
9
10
11
12
/**
Do not return anything, modify s in-place instead.
*/
function reverseString(s: string[]): void {
let left = 0;
let right = s.length - 1;
while(left < right) {
[s[left], s[right]] = [s[right], s[left]];
left++;
right--;
}
};

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.