Home > Back-end >  Leetcode Reverse String problem not accepting in-place solution
Leetcode Reverse String problem not accepting in-place solution

Time:05-07

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?

CodePudding user response:

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]

CodePudding user response:

The first one is not in-place. Your function signature indicates you return nothing yet you do.

CodePudding user response:

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.

  • Related