EASY 0344. Reverse String

Problem Statement

Leetcode Link

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.

Examples

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

Solution
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
"""Solution for Leetcode problem #0344 Reverse String
https://leetcode.com/problems/reverse-string/
"""


def reverse_string(inp_str: list[str]) -> list[str]:
    """Returns a reversed list of chars
    """

    mid = len(inp_str) // 2
    for index in range(mid):
        counterpart = -1 - index
        inp_str[index], inp_str[counterpart] = (
            inp_str[counterpart], inp_str[index]
        )
    return inp_str


def test_reverse_string():
    input_strings = [
        "hello",
        "avengers assemble",
        "there is no cake",
        "hodl"
    ]
    for input_string in input_strings:
        str_list = list(input_string)
        rev_string = list(reversed(str_list))
        assert reverse_string(
            str_list) == rev_string, "Unable to reverse `{}`".format(input_string)

Note

Python specific advice, when you need to do this, just do list[::-1].