Reverse String in three steps - LeetCode 344 - Two Pointers

Reverse String in three steps - LeetCode 344 - Two Pointers

·

1 min read

Hey everyone, Today we will solve LeetCode 344: Reverse String using two pointers approach.

Step 1: Initialize Pointers
we are going to initialize the low at index 0, and the high at the last index.

def reverseString(s):
    low = 0
    high = len(s) - 1

Step 2: Traverse and Swap
we will traverse the array and swap the values after swapping we will increase the low pointer and decrease the high pointer.

def reverseString(s):
    # Initialize pointers at the start (low) and end (high) of the string
    low = 0
    high = len(s) - 1

    # Traverse the string until the two pointers meet
    while low <= high:
        # Swap the characters at the low and high indices
        s[low], s[high] = s[high], s[low]
        # Move the low pointer to the right and high pointer to the left
        low += 1
        high -= 1

# Example 1
s1 = ["h", "e", "l", "l", "o"]
reverseString(s1)
print(s1)  # Output: ["o", "l", "l", "e", "h"]

# Example 2
s2 = ["H", "a", "n", "n", "a", "h"]
reverseString(s2)
print(s2)  # Output: ["h", "a", "n", "n", "a", "H"]

Step 3: Loop Until Pointers Meet
The loop will continue until the pointers meet at the center.

Complexity

Time Complexity: O(n) as the loop runs till `n` times.

Space Complexity: O(1)