DEV Community

Cover image for Reverse String | LeetCode | Python
Retiago Drago
Retiago Drago

Posted on • Edited on

4

Reverse String | LeetCode | Python

The Problem

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.

Constraints

  • 1 <= s.length <= 10^5
  • s[i] is a printable ascii character.

The Input

Sample:

s = ["h","e","l","l","o"]
Enter fullscreen mode Exit fullscreen mode

The Output

Sample:

["o","l","l","e","h"]
Enter fullscreen mode Exit fullscreen mode

Explanation

Already cleared.

The Solution

Pay attention to what in-place algorithm means. One simple solution to do it is swapping both place the former and the latter index of the array until it meets in the middle.

The Code

Source Code 1

class Solution:
    def reverseString(self, s: List[str]) -> None:
        l = len(s)
        for i in range(l//2):
            s[i], s[l-1-i] = s[l-1-i], s[i]
Enter fullscreen mode Exit fullscreen mode

code 1 result

Source Code 2

The same as the previous one but it will only swap if they have not identical values. Hence, it will less swapping and assignment than before.

class Solution:
    def reverseString(self, s: List[str]) -> None:
        l = len(s)
        for i in range(l//2):
            if s[i] != s[l-1-i]:
                s[i], s[l-1-i] = s[l-1-i], s[i]
Enter fullscreen mode Exit fullscreen mode

code 2 result

Original Source

Let's be friend 👋

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging →

Top comments (0)

Neon image

Set up a Neon project in seconds and connect from a Python application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay