Reverse String
The drill: Flip a character array end-to-end by mutating the buffer you were handed — no second array. Encoded here as an array of one-character strings, exactly how LeetCode's Python signature types it.
A buffer of single characters arrives, and the task is to flip it end-to-end so the last character becomes first and the first becomes last, with nothing returned separately.
The array itself is the answer: every character keeps its identity, only positions change, and the reversal has to happen inside the same buffer rather than producing a fresh one.
Whitespace and repeated characters are ordinary members of the array with no special handling; an array of length one or zero simply reverses to itself.
- buffer holds anywhere from zero to a few thousand characters
- characters may repeat and include spaces or punctuation
- the buffer must be edited in place — no second array returned
- extra space beyond a couple of index variables is off budget
HINT 1 THE NUDGE
Building the reversed copy and pasting it back is correct — and it allocates precisely the buffer the follow-up dares you to live without.
HINT 2 THE STRUCTURE
Reversal is nothing but independent swaps: position i trades places with position n−1−i. No intermediate storage is ever required for that trade.
HINT 3 ONE STEP FROM THE ANSWER
Two pointers, one at each end: swap what they hold, step both inward, stop when they meet. The middle element of an odd-length array never has to move.
Two pointers, L at 0 and R at 4 — swap what they hold and step inward.
class Solution:
def reverseString(self, s: List[str]) -> None:
l, r = 0, len(s) - 1
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1class Solution:
def reverseString(self, s: List[str]) -> None:
rev = s[::-1] # the extra buffer the follow-up forbids
for i in range(len(s)):
s[i] = rev[i]class Solution {
public void reverseString(String[] s) {
int l = 0, r = s.length - 1;
while (l < r) {
String tmp = s[l];
s[l] = s[r];
s[r] = tmp;
l++;
r--;
}
}
}class Solution {
public void reverseString(String[] s) {
String[] rev = new String[s.length]; // the extra buffer the follow-up forbids
for (int i = 0; i < s.length; i++) {
rev[i] = s[s.length - 1 - i];
}
for (int i = 0; i < s.length; i++) {
s[i] = rev[i];
}
}
}✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED