344 Reverse String - Easy
Problem:
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.
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"]
Constraints:
1 <= s.length <= 105
s[i]
is a printable ascii character.
Problem Analysis:
-
High-level strategy:
- The solution employs slicing to reverse the list
s
in place. - By using the syntax
s[:]
, it modifies the original lists
instead of creating a new one. s[::-1]
creates a reversed copy of the list, and thens[:]
assigns this reversed copy back to the original list, effectively reversing it in place.
- The solution employs slicing to reverse the list
-
Complexity:
- Time Complexity:
- Reversing the list using slicing
s[::-1]
takes O(n), where n is the length of the lists
. - Assigning the reversed list back to
s
using slicings[:] = ...
also takes O(n), as it iterates through all elements of the list. - Therefore, the overall time complexity is O(n).
- Reversing the list using slicing
- Space Complexity:
- The space complexity is O(1) because the solution modifies the input list in place, without using any additional space proportional to the input size. However, technically, slicing creates a new list, but since it's not stored separately and the original list is modified directly, the space complexity is considered constant, O(1).
- Time Complexity:
Solutions:
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s[:] = s[::-1]