Skip to content
Problem 344 · LeetCode 344(opens in a new tab)

Reverse String

EasyStrings

You are given a string as a list of single characters, s. Reverse it: when you are done, the first character must be the old last one, the second the old second-to-last, and so on.

Change s itself instead of returning a new list, and use only a constant amount of extra memory, no matter how long s is. The function returns nothing.

Example 1

Input:  s = ["p","l","a","n","e","t"]
Output: ["t","e","n","a","l","p"]
Why:    the last character comes first, and so on
2 more examples and the constraints

Example 2

Input:  s = ["N","o","o","n"]
Output: ["n","o","o","N"]
Why:    case is kept; only positions change

Example 3

Input:  s = ["a","b"," ","?"]
Output: ["?"," ","b","a"]
Why:    spaces and symbols are characters too

Constraints

  • 1 ≤ length of s ≤ 100,000
  • Every s[i] is a printable ASCII character (letters, digits, spaces, symbols)

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Reversed copyO(n)
  2. Swap from both endsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeExtra memory for 100,000 charactersVerdict
Reversed copyO(n)
Correct, but uses O(n) extra memory
Swap from both endsO(n)
Best; in place, two counters

n = length of s. Both are linear in time; the bars compare the extra memory.

Edge cases to test

  • One character. left = right = 0, so the loop never runs and s stays as it is.
  • Odd length. In "abcde" the middle c is never swapped; the pointers meet on it and stop.
  • Even length. In "ok" one swap is made, then left = 1 and right = 0 cross and the loop ends.
  • Symbols and spaces. Quotes, spaces and punctuation are ordinary characters and move like letters.

Common mistakes

  • Looping while left <= right or over the whole length, which swaps pairs twice and undoes the work.
  • Returning a reversed copy instead of changing s, so the caller still sees the old order.
  • Swapping with s[n - i] instead of s[n - 1 - i], which reads one past the end.

How to talk through it

  1. 1Clarify. Do I change s in place and return nothing? Is a single character allowed?
  2. 2Name the easy way. A reversed copy written back works in O(n) time, but it needs O(n) extra memory.
  3. 3Pair up mirrors. Index i and index n − 1 − i trade places, so two pointers from the ends can swap pair by pair.
  4. 4State the cost. n / 2 swaps, O(n) time, and only two counters, so O(1) extra space.
  5. 5Test out loud. Run one character, an even length like "ok", and an odd one like "abcde".
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?