Reverse a String easy
Description
Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory.
Examples
> Case 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
> Case 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]Constraints
1 <= s.length <= 10^5s[i]is a printable ASCII character
Approach 1: Two Pointers (Optimal)
The classic two-pointer approach: one pointer starts at the beginning, the other at the end. Swap and move inward until they meet.
Reversing "hello" with two pointers
Step 1 of 3
h
[0]e
[1]l
[2]l
[3]o
[4]left=0, right=4. Swap 'h' and 'o'.
Explanation
- Initialize two pointers:
leftat position 0 andrightat the last position - While
left < right, swap the characters at these two positions - Move
leftforward andrightbackward - When the pointers meet or cross, every character has been swapped and the string is reversed
Why this is problem #1 for strings: This two-pointer swap technique is the foundation of dozens of problems. Palindrome checking, partitioning, and the Dutch National Flag problem all use the same core idea.
Analysis
- Time Complexity:
O(n)— each character is visited once - Space Complexity:
O(1)— only uses two pointer variables