ReverseString
Problem
Solution
Let \(n\) be the length of the input list s
. Let end = n - 1
. We
can reverse the list by swapping the outermost elements, moving inwards.
s[i], s[end - i] = s[end - i], s[i]
Code
https://github.com/GeorgeRPu/tech-interview-prep/blob/main/solutions/ReverseString.py
def reverseString(s):
"""
Do not return anything, modify s in-place instead.
"""
end = len(s) - 1
for i in range(len(s) // 2):
s[i], s[end - i] = s[end - i], s[i]
Test
>>> from ReverseString import reverseString
>>> s = ['h', 'e', 'l', 'l', 'o']
>>> reverseString(s)
>>> s
['o', 'l', 'l', 'e', 'h']
>>> s = ['H', 'a', 'n', 'n', 'a', 'h']
>>> reverseString(s)
>>> s
['h', 'a', 'n', 'n', 'a', 'H']
Functions
|
Do not return anything, modify s in-place instead. |