'Leetcode Reverse String problem not accepting in-place solution
I am posting two solutions below which I tried in leetcode for the problem no : 344
https://leetcode.com/problems/reverse-string/
Solution 1
class Solution:
def reverseString(self, s: List[str]) -> None:
return s[::-1]
Solution 2
class Solution:
def reverseString(self, s: List[str]) -> None:
first = 0
last = len(s) - 1
while first <= last:
s[first], s[last] = s[last], s[first]
first += 1
last -= 1
return s
As I understand, both solutions are in-place. However, solution 1 is not accepted and prompts as wrong answer. Solution 2 is accepted. Could someone help me out?
Solution 1:[1]
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]
Solution 2:[2]
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.
Solution 3:[3]
The first one is not in-place. Your function signature indicates you return nothing yet you do.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Deepak Tripathi |
| Solution 2 | |
| Solution 3 | mike3996 |
