Home > Back-end >  Why does my solution to reverse a list of characters in-place not work?
Why does my solution to reverse a list of characters in-place not work?

Time:04-01

I'm doing this exercise:

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.

My solution that does not work:

def reverseString(s: List[str]) -> None:
    """
    Do not return anything, modify s in-place instead.
    """
    s = s[::-1]

Correct answer:

def reverseString(s: List[str]) -> None:
    """
    Do not return anything, modify s in-place instead.
    """
    s[::] = s[::-1]

Why does my solution not work?

CodePudding user response:

The expression s[::-1] will create a new list with its elements reversed.

Then,

s[:] = s[::-1]

...causes the new list to be copied into the address space previously occupied by the original list whereas...

s = s[::-1]

Assigns a reference to the reversed list to a local variable s.

As an aside and because I don't know what "O(1) extra memory" means, it's worth noting that the functionally correct answer does require duplication of the memory used by the original list whereas...

def reverseString(s):
    i = 0
    j = len(s) - 1
    while i < j:
        s[i], s[j] = s[j], s[i]
        i  = 1
        j -= 1

...does not because it's swapping elements in situ

CodePudding user response:

You have to do an in-place modification.

S[::] = is doing the modification on actual memory byte of s while s = s[::-1] is pointing the variable name s and not doing any modification.

CodePudding user response:

Reassigning the list inside the function will not change the original list, s[:] = or s[::] = slice-assigns, replacing what was previously in the list

  • Related