DSA AnimatorREVISION VIDEOS
← Back to problems
New

Reverse String — LeetCode 344 video explanation

Reverse an array of characters in place. You must use only constant extra memory.

Loading videos…

DSA Animator › DSA Revision › Strings › Reverse String

Key moments in the Reverse String video

0:04Problem0:09Example0:12Brute force0:20Key idea0:27Dry run0:38Code0:50Takeaway

What you will learn

Remember: in-place reversal is two pointers swapping toward the middle. The same move appears inside many harder problems. The video solves Reverse String (LeetCode 344, Easy) with the Two Pointers pattern from the Strings topic, and you can replay every step in the interactive Reverse String animation.

Reverse String video transcript

Problem

Reverse an array of characters in place. You must use only constant extra memory.

Example

h, e, l, l, o becomes o, l, l, e, h.

Brute force

Copying the characters into a new array backwards uses O of n extra space. The problem asks you to work in place.

Key idea

Put one pointer at each end. Swap the two characters, then move both pointers inward. Stop when they meet.

Dry run

Swap h and o, giving o, e, l, l, h. Move inward and swap e and l, giving o, l, l, e, h. The pointers meet at the middle l, which stays where it is. The array is reversed.

Code

In code, set left to 0 and right to the last index. While left is less than right, swap and move both pointers. Each character is touched once, so it's O of n time and O of 1 space.

Takeaway

Remember: in-place reversal is two pointers swapping toward the middle. The same move appears inside many harder problems.

More Strings revision videos

← All 185 DSA revision videos