Friedrich Ewald My Personal Website

Leetcode: Reverse string

Reverse a string and only use one extra variable. The solution is straightforward with two pointers, p1 and p2. THe idea here is to start from both ends and increment p1 and decrement p2 until both of them meet in the middle. To switch the values of variables without assigning a temporary variable, the notation of a, b = b, a can be used. To convert a string into a list of characters, surroung the string with [*s].

from typing import List, Optional

class Solution:
  def reverseString(self, s: List[str]) -> None:
    Do not return anything, modify s in-place instead.
    p1 = 0
    p2 = len(s) - 1
    while p1 < p2:
      s[p1], s[p2] = s[p2], s[p1]
      p1 += 1
      p2 -= 1

if __name__ == '__main__':
  s = Solution().reverseString
  t = [*'Hello world']
  print(s(t), t)
  t = [*'AB']
  print(s(t), t)
Runtime: 377 ms, faster than 22.88% of Python3 online submissions for Reverse String. Memory Usage: 18.4 MB, less than 45.70% of Python3 online submissions for Reverse String.

About the author

is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.