Reverse String — Understanding the Two Pointers Technique
LeetCode 344: trace the swaps, understand the stopping condition, and reverse a character array in place.
- Platform
- LeetCode
- Problem number
- 344
- Problem difficulty
- Easy
- Pattern
- Two Pointers — Opposite Direction
- Solution language
- Python 3
Problem overview
We are given a mutable list of characters. The task is to put those same characters into reverse order by changing the existing list, using a fixed amount of extra storage.
The important constraint is “in place”. Building a second reversed list would produce the right characters but would use extra storage proportional to the input length. The official problem allows 1 to 100,000 printable ASCII characters.
Example input and output
Input: ["h", "e", "l", "l", "o"]
Output: ["o", "l", "l", "e", "h"]The first and last characters exchange places, then the next pair does the same. The middle “l” stays at index 2.
Reasoning Before Coding
Before coding, it helps to ask three questions: which two positions belong together, how can I exchange their values without losing either one, and when is there nothing left to exchange?
Handwritten reasoning — image to be addedThis space is reserved for the original notebook photograph. The written explanation and result are included below.
Two Pointers: work from the outside in
Reversal pairs index k with index n − 1 − k. This gives us a natural left pointer and right pointer. Once their characters have been exchanged, both positions are finished and we can focus on the smaller section between them.
index 0 1 2 3 4
array h e l l o
↑ ↑
i j
swap 0 ↔ 4: o e l l h
swap 1 ↔ 3: o l l e h
↑
i = jStage | i | j | Values swapped | Array after the step |
|---|---|---|---|---|
Start | 0 | 4 | — | ["h", "e", "l", "l", "o"] |
First swap | 0 → 1 | 4 → 3 | "h" ↔ "o" | ["o", "e", "l", "l", "h"] |
Second swap | 1 → 2 | 3 → 2 | "e" ↔ "l" | ["o", "l", "l", "e", "h"] |
Stop | 2 | 2 | No swap: i < j is false | ["o", "l", "l", "e", "h"] |
The loop invariantBefore each iteration, every position to the left of i and to the right of j already contains its final reversed character. Only the section from i to j remains to be processed.
My original Python solution
This is the submitted approach, including the initial temp assignment and return statement. The refined version later in this note is a separate cleanup.
class Solution:
def reverseString(self, s: list[str]) -> None:
i = 0
j = len(s) - 1
temp = 0
while j > i:
temp = s[j]
s[j] = s[i]
s[i] = temp
i += 1
j -= 1
return sStep-by-step code explanation
1. Start at the first and last valid indices
Python lists are indexed from zero, so i = 0 points to the first character. A list of length n ends at index n − 1; j = len(s) − 1 points to the last character. Using len(s) itself would try to access a position beyond the list.
2. Keep going only while i < j
The submitted condition j > i means exactly the same thing as i < j. It ensures we process each pair once. With an odd-length list, the pointers meet on the centre character. With an even-length list, they cross after the final pair. Both cases stop the loop.
Using i <= j would add an unnecessary self-swap at the centre of an odd-length list. Continuing after the pointers cross would begin undoing the earlier swaps.
3. Save one character before overwriting its cell
temp = s[j] saves the character on the right. Then s[j] = s[i] copies the left character into the right position. Finally s[i] = temp puts the saved right character into the left position.
temp = s[j] # Save "o".
s[j] = s[i] # Right cell becomes "h".
s[i] = temp # Left cell becomes the saved "o".Without temp, assigning s[i] = s[j] after the second line would copy “h” back to the left. Both cells would contain “h”, and the original “o” would have been lost.
4. Move into the remaining section
i += 1 moves one position to the right, and j -= 1 moves one position to the left. The completed pair is left alone. Each pass shrinks the unprocessed section by two characters, so the loop makes progress toward meeting or crossing.
5. Change the original list
Assignments such as s[j] = s[i] replace items inside the list that the caller supplied. The function never rebinds s to a new list. The caller therefore observes the reversal on the same list object.
A refined version
Two details can be removed. temp = 0 is redundant because temp is assigned from s[j] before every use; if the loop never runs, temp is never needed. LeetCode asks for a None return and checks the modified input. The accepted submission returns s, but the clearer implementation omits that return and lets Python return None.
class Solution:
def reverseString(self, s: list[str]) -> None:
i = 0
j = len(s) - 1
while i < j:
temp = s[j]
s[j] = s[i]
s[i] = temp
i += 1
j -= 1The cleanup changes neither the swapping algorithm nor its complexity. It makes the implementation match the stated function contract.
Interactive pointer walkthrough
Watch the intermediate assignments as well as the completed swaps. In particular, notice the moment when two cells contain the same character: the other character is still safe in temp.
Follow every assignment.
Reverse String · opposite-direction two pointers
The interactive controls require JavaScript. The complete trace is available below.
| Step | Array and pointers | Operation and explanation |
|---|---|---|
| 1 | ["h","e","l","l","o"]i=0, j=4 temp=—, i < j=true | i = 0; j = len(s) - 1Start at the two ends. Check i < j before swapping anything. |
| 2 | ["h","e","l","l","o"]i=0, j=4 temp=o, i < j=true | temp = s[j]Save 'o' from index 4 before overwriting that cell. |
| 3 | ["h","e","l","l","h"]i=0, j=4 temp=o, i < j=true | s[j] = s[i]Copy 'h' from index 0 to index 4. The saved 'o' is still safe in temp. |
| 4 | ["o","e","l","l","h"]i=0, j=4 temp=o, i < j=true | s[i] = tempWrite 'o' into index 0. This pair is now in its final reversed positions. |
| 5 | ["o","e","l","l","h"]i=1, j=3 temp=o, i < j=true | i += 1; j -= 1Move inward to indices 1 and 3. Everything outside the pointers is finished. |
| 6 | ["o","e","l","l","h"]i=1, j=3 temp=l, i < j=true | temp = s[j]Save 'l' from index 3 before overwriting that cell. |
| 7 | ["o","e","l","e","h"]i=1, j=3 temp=l, i < j=true | s[j] = s[i]Copy 'e' from index 1 to index 3. The saved 'l' is still safe in temp. |
| 8 | ["o","l","l","e","h"]i=1, j=3 temp=l, i < j=true | s[i] = tempWrite 'l' into index 1. This pair is now in its final reversed positions. |
| 9 | ["o","l","l","e","h"]i=2, j=2 temp=l, i < j=false | i += 1; j -= 1Both pointers reach index 2. The centre character stays where it is. |
| 10 | ["o","l","l","e","h"]i=2, j=2 temp=l, i < j=false | i < j → FalseStop. No more swaps are needed; the original array has been reversed. |
Time and space complexity
Measure | Cost | Reason |
|---|---|---|
Time | O(n) | There are floor(n / 2) swaps. Each swap and pointer update takes constant time. |
Auxiliary space | O(1) | Only i, j and one saved character are needed, regardless of the list length. The input list is modified directly. |
Visiting roughly half of the positions as pairs does not make the cost O(log n). n / 2 still grows linearly with n. The input list is not counted as auxiliary storage.
Edge cases
Input | What happens | Result |
|---|---|---|
["a"] | i and j start at 0. The loop never executes. | ["a"] |
["a", "b"] | One swap, then the pointers cross. | ["b", "a"] |
["a", "b", "c", "d"] | Two swaps. There is no untouched centre cell. | ["d", "c", "b", "a"] |
["a", "b", "a"] | Equal values still follow the same swapping rule. | ["a", "b", "a"] |
["A", " ", "!"] | Spaces and punctuation are ordinary characters. | ["!", " ", "A"] |
An empty list is outside this problem’s stated constraints. The same code would nevertheless skip the loop because i = 0 and j = −1.
Check your understandingFor ["a", "b", "c", "d"], where are i and j after two swaps? They are 2 and 1. They have crossed, so i < j is false. For a five-character input, why is the centre left alone? Reversal maps the centre index back to itself.
Implementation and Result
The supplied accepted-result screenshot records the following submission on 17 November 2026. The figures below come from that screenshot; they are observations from a single run.
Result | Recorded value |
|---|---|
Status | Accepted |
Test cases | 477 / 477 passed |
Runtime | 1 ms |
Memory | 23.59 MB |
Language | Python 3 |
Accepted submission screenshot — image to be addedThis space is reserved for the original accepted-submission screenshot. The written explanation and result are included below.
Runtime and memory measurements can vary with the execution environment and between runs. The reason for choosing this approach is its O(n) time and O(1) auxiliary space, together with a straightforward correctness argument.
What I learned
This problem helped me practise opposite-direction pointers, in-place swapping and loop termination conditions. I first traced the pointer movement on paper, then translated the reasoning into Python and submitted the solution.
Pair each position with the corresponding position from the other end.
Keep one value safe before overwriting its location.
State what is already finished before moving the pointers.
Treat the stopping condition as part of the reasoning, rather than as a detail to guess.