Reverse a Python list in place with two pointers and swaps in O(n) time and O(1) extra space — no reverse() or slicing. Live tests check it mutates the input.
The problem
Reverse nums in place (modify the list itself) and return it. Don't use reverse(), reversed() or slicing.
Examples
Example 1
Input
reverse_in_place([1, 2, 3, 4])
Expected output
[4, 3, 2, 1]
Example 2
Input
reverse_in_place([1, 2, 3])
Expected output
[3, 2, 1]
+ 2 hidden tests on Submit — original list is changed.
Edge cases to ask about
- Empty
- Odd length
- Even length
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.
Pick both to reveal the answer.
Measure it
Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| Build a reversed copy | O(n) | O(n) | Not in place. |
| bestSwap from both ends | O(n) | O(1) | Tuple assignment swaps without a temp variable. |
Walkthrough of the optimal approach (try it yourself first)
Two pointers at the ends, swap, move inward, stop when they meet. nums[i], nums[j] = nums[j], nums[i] swaps without a temp variable. Returning a new list (nums[::-1]) would not be in place — the hidden test checks the original list changed.
Complexity: O(n) time, O(1) space. n / 2 swaps; only two indices of extra memory.
Reveal the reference solution
def reverse_in_place(nums): i, j = 0, len(nums) - 1 while i < j: nums[i], nums[j] = nums[j], nums[i] i += 1 j -= 1 return nums
Follow-ups interviewers ask
- Reverse only the sub-range i..j.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Reverse a List In Place in Python?
The optimal solution runs in O(n) time and O(1) auxiliary space. n / 2 swaps; only two indices of extra memory.
What is the brute-force approach, and how do you optimise it?
Build a reversed copy: O(n) time, O(n) space. Not in place. Swap from both ends: O(n) time, O(1) space. Tuple assignment swaps without a temp variable.
What follow-up questions do interviewers ask about Reverse a List In Place?
Reverse only the sub-range i..j.
