call(back)
Algorithms & Data StructureseasySign in to star problemsSign in to track progress

Does This In-Place Reverse Work?

Consider this attempt to reverse an array A of length n in place:

for i = 0, 1, ..., n - 1:
    swap(A[i], A[n - 1 - i])

Answer verbally: does it always reverse the array correctly, and why? If not, how should the iteration range change? What are the time and auxiliary space complexities of the corrected version? Consider empty arrays, one element, and odd and even lengths.

This opens the Karat screen, before any code is written.

Hints

Hint 1

Trace [1, 2, 3, 4]: after i = 1 the array is reversed; what do i = 2 and i = 3 do?

Solution

Show the approach

Answer

No. Each pair (i, n - 1 - i) is visited twice, once from each end, so the second visit swaps it back and the array ends unchanged (for odd n the middle element is swapped with itself, which is harmless). Iterate only over the first half, i < n / 2 (integer division): [1, 2, 3, 4] swaps (0, 3) and (1, 2) and stops; [1, 2, 3] swaps (0, 2) and leaves the middle alone. Empty and single-element arrays make zero iterations. The corrected loop is O(n) time and O(1) auxiliary space.

Worth saying out loud

  • The bug is a symmetry bug, not an off-by-one; saying so shows you understand why the half-range fixes it.
  • Two pointers moving inward until they meet is the same loop written without the index arithmetic.

Assistant

Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.

Topics

Asked at

Similar Problems6