-1
class Solution:
    def reverseString(self, s: List[str]) -> None:
        if(len(s)<=1):
            return
        s[0],s[-1] = s[-1],s[0]
        self.reverseString(s[1:-1])

this was a question on LeetCode. We have to reverse the list using recursion without using extra memory, i.e in-place.

I wrote this code but I am not sure why it is not working. For example, when s = ['h', 'e', 'l', 'l', 'o'], the output is ['o', 'e', 'l', 'l', 'h'] instead of ['o', 'l', 'l', 'e', 'h'] - it only swaps the first and last elements of the list.

kaya3
  • 47,440
  • 4
  • 68
  • 97

2 Answers2

1

The following works for me:

def reverse_inplace(char_list, step=1):
    start, stop = step - 1, -step
    if step == 1:
        pass
    elif len(char_list[start:stop]) <= 1:
        return
    char_list[start], char_list[stop] = char_list[stop], char_list[start]
    reverse_inplace(char_list, step=step+1)

This passes the same list reference to each recursive call, and simply keeps track of how far along you are in the process with a step parameter.

reverse_inplace(list("hello")) outputs:

['o', 'l', 'l', 'e', 'h']
PMende
  • 5,171
  • 2
  • 19
  • 26
0

Kind of a fix for your concept:

def reverseString(s, n=0):
    if(n==len(s)//2):
        return
    else:
        s[n], s[-n-1]=s[-n-1], s[n]
        reverseString(s, n+1)

x=list("new york")
reverseString(x)
print(''.join(x))
#outputs: kroy wen
x=list("hello")
reverseString(x)
print(''.join(x))
#outputs: olleh
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34