Write a function that reverses a string. The input string is given as an array of characters
You must do this by modifying the input array in-place with
Output: ["o","l","l","e","h"]
Output: ["h","a","n","n","a","H"]
Constraints:
1 <= s.length <= 105 s[i] is a printable ascii character.
Contents
Solution 1 - Swap characters from both sides using two pointers
In this approach, we will use two pointers to point to both ends of input string
Implementation steps:
-
Create two pointer variables
i andj to point to left and right ends of input strings characters. -
Then, run a
while loop untili andi don't intersect with each other, then swap the characters at these indexes, and increment left pointeri and decrement right pointerj .
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1).
Above implementations source code can be found at