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 👋

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay