Reverse String

Easy

Topics
StringTwo Pointers

Given a string s, return the string reversed.

Example 1

inhlellor
outolleh
It must happen in place, so building a reversed copy does not count.
Rows are the string before and after reversal.
Input:  s = "hello"
Output: "olleh"

Example 2

inalbcdr
outdcba
Input:  s = "abcd"
Output: "dcba"

Constraints

  • 1 <= s.length <= 10^5
  • s consists of printable ASCII letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Reversing is a two-pointer swap: exchange the ends and walk inward until the pointers meet. Each character moves exactly once and nothing is allocated.

The shown one-liner s[::-1] is clear and idiomatic in Python, but it builds a new string. That matters because the canonical form of this problem asks you to modify a character array in place with O(1) extra space — which is exactly what the two-pointer version delivers and the slice does not.

Approach

  1. left = 0, right = n - 1.
  2. While left < right: swap, then move both inward.

Dry Run

['h','e','l','l','o']

left=0 right=4   swap h/o   ['o','e','l','l','h']
left=1 right=3   swap e/l   ['o','l','l','e','h']
left=2 right=2   pointers meet, stop

answer "olleh"

note the middle character of an odd-length string is
never swapped, which is correct -- it is already in place

Complexity

  • Time — O(n): n/2 swaps.
  • Space — O(1) for the two-pointer version. The s[::-1] form shown is O(n) because it allocates the result — and Python strings are immutable, so a genuinely in-place reverse requires a list of characters. Worth stating plainly rather than claiming O(1) for a slice.

Common Pitfalls

  • Looping to n rather than stopping at the midpoint, which swaps every pair twice and returns the original string.
  • Using left <= right, which pointlessly swaps the middle element with itself — harmless here, but a sign the invariant is not clear.
  • Claiming O(1) space for a slice or for "".join(reversed(s)); both allocate.
  • Reversing a Python string in place. They are immutable; convert to a list first.

Full Solution — all languages

class Solution:
    def reverseString(self, s):
        return s[::-1]
Asked at Qualcomm TCS Wipro
SensAI
Beta
Tap the mic to stop voice mode