Skip to content

Latest commit

 

History

History
112 lines (91 loc) · 2.54 KB

2022-02-01-102314-344_reverse_string.org

File metadata and controls

112 lines (91 loc) · 2.54 KB

344 Reverse String

Description

Write a function that reverses a string. The input 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. $1 \leq s.length \leq 105$
  2. s[i] is a printable ascii character

Examples:

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

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

Solution

Understanding the problem

Algorithm

We can have two pointers left_idx = 0 and right_idx = len(s) and swap s[left_idx] and s[right_idx]. Then left_idx += 1, right_idx -= 1, until left_idx == right_idx.

Code

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

    left_idx = 0
    right_idx = len(s) -1

    while left_idx < right_idx:
        s[left_idx], s[right_idx] = s[right_idx], s[left_idx]
        left_idx += 1
        right_idx -= 1



# tests
s = ["h","e","l","l","o"]
reverseString(s)
print(s == ["o","l","l","e","h"])

s = ["H","a","n","n","a","h"]
reverseString(s)
print(s == ["h","a","n","n","a","H"])

Complexity

Time complexity:

O(N)

Space complexity:

O(1)

Leetcode solution

Recursion or two pointers.

<<imports for typing>>

Time complexity:

Space complexity:

More analysis

General thoughts

See also: In-place algorithm.

Related problems

Log time