344. Reverse String
Asked at 15Bloomberg55Google47Amazon46Microsoft46Apple43Meta39Qualcomm82tcs70Siemens65Wipro63EPAM Systems60HCL60Accenture44Nvidia39Goldman Sachs28
Problem
Reverse the character array s in place.
Example: ["h","e","l","l","o"] → ["o","l","l","e","h"]
Constraints: O(1) extra memory.
Swap from both ends towards the middle.
Complexity: O(n) time, O(1) space.
class Solution:
def reverseString(self, s: List[str]) -> None:
l, r = 0, len(s) - 1
while l < r:
s[l], s[r] = s[r], s[l]
l, r = l + 1, r - 1
a = list("hello"); Solution().reverseString(a)
assert a == list("olleh")
a = list("Hannah"); Solution().reverseString(a)
assert a == list("hannaH")
a = ["x"]; Solution().reverseString(a)
assert a == ["x"]
class Solution {
public void reverseString(char[] s) {
for (int l = 0, r = s.length - 1; l < r; l++, r--) { char t = s[l]; s[l] = s[r]; s[r] = t; }
}
}
func reverseString(s []byte) {
for l, r := 0, len(s)-1; l < r; l, r = l+1, r-1 {
s[l], s[r] = s[r], s[l]
}
}