[Leet Code] Reverse String

Matthew Boyd
2 min readJan 13, 2021

--

Leetcode: https://leetcode.com/problems/reverse-string/

Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

Example 1:

Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

Solution:

class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""

write_pointer = len(s) -1

for i in range(len(s) / 2):
temp_val = s[i]
s[i] = s[write_pointer]
s[write_pointer] = temp_val
write_pointer -= 1

Explanation:

For this solution, we’re going to create a writer pointer, we’re essentially going to go through each of the values and swap them with their counterpart at the end of the list. This can be seen below:

We have to store the first value in a temporary value so that we don’t lose it, then we assign the last value to the first value, and then we assign the temp_val as the last value, therefore effectively we’ve swapped the values of 1 and len(arr) -1. We continue to do this over len / 2 as we only have to do half the string as we’re doing two operations in each iteration.

--

--

Matthew Boyd
Matthew Boyd

Written by Matthew Boyd

Learning, and posting my findings!

No responses yet