Reverse String

two-pointers

Description

Given a string s, reverse it in place. Return the reversed string.

Example 1:
Input: s = "hello"
Output: "olleh"

Example 2:
Input: s = "Hannah"
Output: "hannaH"

Example 3:
Input: s = "a"
Output: "a"
Explanation: Single character remains the same when reversed.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of printable ASCII characters

Complexity

Show Complexity
  • Time: O(n)
  • Space: O(1)

Hints

Show Hints
Pattern
Use two pointers: one at start, one at end
Approach
Swap characters at left and right pointers, then move them toward center
Complexity
Swap elements in place to achieve O(1) extra space

Solutions

Show C Solution
char *solution(char *s) {
  if (s[0] == '\0')
    return s;

  size_t i = 0;
  size_t j = strlen(s) - 1;

  while (i < j) {
    char temp = s[i];
    s[i] = s[j];
    s[j] = temp;
    i++;
    j--;
  }

  return s;
}
Show PY Solution
def solution(s):
    if len(s) == 0:
        return s

    ls = list(s)
    i = 0
    j = len(ls) - 1
    while i < j:
        ls[i], ls[j] = ls[j], ls[i]
        i += 1
        j -= 1
    return "".join(ls)