In-Place Array Reversal: Why Swapping Every Index With Its Mirror Fails
Company: Duolingo
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: easy
Interview Round: Technical Screen
A teammate wants to reverse an array in place. Their code walks over every index `i` from `0` to `n - 1` and swaps `a[i]` with its mirror element `a[n - 1 - i]`:
```python
def reverse_in_place(a):
n = len(a)
for i in range(n):
a[i], a[n - 1 - i] = a[n - 1 - i], a[i]
```
Does this reverse the array correctly? If not, explain what it actually does, fix it, and give the time and space complexity of the fixed version. This was asked as a verbal question, without running any code.
```hint Trace a small case
Run the loop by hand on `[1, 2, 3, 4]` and follow what happens to the pair at positions 0 and 3 over the whole loop.
```
### Clarifying Questions
- Does "in place" mean $O(1)$ extra space?
- Can the array be empty, and can its length be odd?
### What a Strong Answer Covers
- A correct verdict with a precise explanation of why, based on tracing the loop
- What the loop actually leaves behind
- A fix with the right loop bound, including the middle element of an odd-length array
- Time and space complexity of the fix, and the observation that complexity alone does not reveal the bug
- Edge cases: empty, single-element and odd-length arrays
### Follow-up Questions
- Rewrite the fix with two pointers moving toward each other. Should the loop condition use `<` or `<=`, and does it matter?
- How would you reverse only the elements between indices `l` and `r`?
- How would you rotate an array to the right by `k` positions in place, with $O(1)$ extra space?
Overview: A verbal algorithm question about reversing an array in place: does a loop that swaps every index with its mirror position work, what does it actually do, and how should it be fixed. It tests careful tracing of simple code, loop bounds, and time and space complexity.
Read the full Duolingo Software Engineer interview experience this question came from