Skip to content

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:

Example 1:

**Input:** s = ["h","e","l","l","o"]
**Output:** ["o","l","l","e","h"]

Solve

Create temporary/stored memory

Create tmp string, process to reversed it’s order, and re-update s after

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        tmp = s[::-1]
        for i,c in enumerate(tmp):
            s[i] = c
        return s

equal c code

void reverseString(char* s, int sSize){
    char* tmp = (char*)malloc(sSize * sizeof(char));
    for (int i = 0; i < sSize; i++) {
        tmp[i] = s[sSize - i - 1];
    }

    for (int i = 0; i < sSize; i++) {
        s[i] = tmp[i];
    }

    free(tmp);
}

Reverse in-place

We can start from both of the start and the end of string. Swap them, go to the next pair and stop at the middle of the string

class Solution(object):
    def reverseString(self, s):
        for i in range(len(s)//2):
            s[i], s[len(s) -1 - i] = s[len(s) -1 - i], s[i]

equal c code

void reverseString(char* s, int sSize){
    if (sSize == 0){
        return;
    }
    for (int i = 0 ; i < sSize/2 ; i++){
        char tmp = s[i];
        s[i] = s[sSize-1-i];
        s[sSize-1-i] = tmp;
    }
}


Last update : October 13, 2023
Created : August 16, 2023