LeetMotion
Write a function that reverses a string in-place. 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.
s[i] is a printable ASCII character.The most intuitive approach is to build a new reversed array from the original, then copy the values back. This violates the O(1) space requirement.
Why it's not optimal: Uses O(n) extra space for the copy, violating the in-place constraint.
def reverseString(s): rev = s[::-1] for i in range(len(s)): s[i] = rev[i]
Place one pointer at the start and one at the end. Swap their characters and move both pointers inward until they meet in the middle.
L=0 and R=len(s)-1.L < R, swap s[L] and s[R].L and decrement R to move inward.
Discussion
…