Question is saying do not return anything that means you need to do inplace reversing. Also this is list of string not a string so whatever you change inside function it will be reflected in the list because lists are mutable.
Correct Solution will be
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
Also If you want to do in your style then correct line will be
s[:] = s[::-1]
Answer from Deepak Tripathi on Stack OverflowSo the code goes:
s = [โhโ, โeโ, โlโ, โlโ, โoโ]
s[:] = s[::-1] print(s)
This prints the reverse of s in both VSCode and on the LeetCode website ide
I tried to see if the follow would work:
s = [โhโ, โeโ, โlโ, โlโ, โoโ]
s = s[::-1] print(s)
This did work but only on VSCode not on leet code. So my question is why did it work in VSCode and not LeetCode?
Thereโs other solutions I tried to the problem that work in VSCode but not in LeetCode shock I find it odd, am I doing something I shouldn't?
Videos
Question is saying do not return anything that means you need to do inplace reversing. Also this is list of string not a string so whatever you change inside function it will be reflected in the list because lists are mutable.
Correct Solution will be
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
Also If you want to do in your style then correct line will be
s[:] = s[::-1]
The first solution creates a new list and does not change the parameter (which also feels cleaner).
Edit: Never mind the following part. It won't do anything. Thanks.
However you could do something like
s = s[::-1]
instead of the return statement.
To do this without space, you need to swap. You can't add array slices. Instead of splitting the indexes in the middle, which will never let you swap opposite pairs (expect in the base case).
You can see it, if you imagine the recursion visually. You start with a list like:
1, 2, 3, 4
^ ^ <-- these need to swap in a reverse
But after your first recursive call you split this into:
---- | ----
1, 2 3, 4
^ ^ <-- these still need to be swapped, bu when?
Now branch one has no way to get at the 4 in branch two to swap unless there's a non-obvious way to do it as the recursion unwinds.
You can instead (much more easily) walk you indexes in from both ends and swap as you go. Then your base case is just when they meet in the middle:
class Solution:
def reverseString(self, s, lo=0, hi=None):
if hi == None:
hi = len(s) - 1
if hi <= lo:
return s
s[lo], s[hi] = s[hi], s[lo]
return self.reverseString(s, lo + 1, hi - 1)
s = Solution()
s.reverseString([1, 2, 3, 4])
# [4, 3, 2, 1]
s.reverseString([1, 2, 3, 4, 5])
#[5, 4, 3, 2, 1]
I am not sure why are you doing recursion. You can simply take two pointers, one at the start and one at the end of the string, start by swapping those characters, and move the pointers towards each other, until they cross, and then you break and return the reversed string.
class Solution:
def reverseString(self, s):
if len(s) <= 1: return s
# The two pointers
lo = 0
hi = len(s) - 1
# Iterate till both pointers cross
while lo < hi:
# swap the characters
tmp = s[lo]
s[lo] = s[hi]
s[hi] = tmp
# increment the pointers
lo += 1
hi -= 1
return s
s = Solution()
print(s.reverseString(['h']))
print(s.reverseString(["h","e","l","l","o"]))
print(s.reverseString(["h","e","l","l","o","w","o","r","l","d"]))
#['h']
#['o', 'l', 'l', 'e', 'h']
#['d', 'l', 'r', 'o', 'w', 'o', 'l', 'l', 'e', 'h']
In addition, the recursive approach for the same is as follows
class Solution:
def reverseString(self, s, lo=0, hi=None):
#If one character or less in the string, return the string
if len(s) <= 1:
return s
#The last index should be placed at the end of the string
if hi == None:
hi = len(s) - 1
#If the two indexes cross, return the string
if hi < lo:
return s
#swap the low and high characters
tmp = s[lo]
s[lo] = s[hi]
s[hi] = tmp
#Recursively call the function
return self.reverseString(s, lo + 1, hi - 1)
s = Solution()
print(s.reverseString(['h']))
print(s.reverseString(["h","e","l","l","o"]))
print(s.reverseString(["h","e","l","l","o","w","o","r","l","d"]))
#['h']
#['o', 'l', 'l', 'e', 'h']
['d', 'l', 'r', 'o', 'w', 'o', 'l', 'l', 'e', 'h']
Python string is not mutable, so you can not use the del statement to remove characters in place. However you can build up a new string while looping through the original one:
def reverse(text):
rev_text = ""
for char in text:
rev_text = char + rev_text
return rev_text
reverse("hello")
# 'olleh'
The problem is that you can't use del on a string in python.
However this code works without del and will hopefully do the trick:
def reverse(text):
a = ""
for i in range(1, len(text) + 1):
a += text[len(text) - i]
return a
print(reverse("Hello World!")) # prints: !dlroW olleH
Thanks all. The solution was to add a parameter with a default, to get over the issues with the leetcode test harness, so now I can do it as below:
class Solution:
def reverseString(self, s: List[str], start = 0) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if len(s[start:len(s)-start]) <= 1:
return
end = len(s) - start - 1 # end postition
temp = s[start]
s[start] = s[end]
s[end] = temp
self.reverseString(s, start+1)
From what i understood, the solution should be recursive. Try this:
EDIT: (as should look in leetcode)
def reverseStringHelper(s, index):
length = len(s)
if index >= length / 2:
return
temp = s[index]
s[index] = s[length - 1 - index]
s[length - 1 - index] = temp
reverseString(s, index + 1)
def reverseString(s):
reverseStringHelper(s, 0)
Defining arr = ['h', 'e', 'l', 'l' ,'o'] and calling reverseString(arr, 0) will result in ['o', 'l', 'l', 'e', 'h']
You may call it from a different function so it would only accept the list.