How can you reverse an array in-place?

Arrays Linked Lists Questions Medium



46 Short 80 Medium 67 Long Answer Questions Question Index

How can you reverse an array in-place?

To reverse an array in-place, we can use a two-pointer approach. We initialize two pointers, one pointing to the start of the array (let's call it "left") and the other pointing to the end of the array (let's call it "right"). We swap the elements at these two pointers and then move the left pointer one step forward and the right pointer one step backward. We repeat this process until the left pointer surpasses the right pointer.

Here is the step-by-step algorithm to reverse an array in-place:

1. Initialize a variable "left" to 0, pointing to the start of the array.
2. Initialize a variable "right" to the length of the array minus 1, pointing to the end of the array.
3. While the "left" pointer is less than the "right" pointer, do the following steps:

a. Swap the elements at the "left" and "right" pointers.
b. Increment the "left" pointer by 1.
c. Decrement the "right" pointer by 1.
4. Once the "left" pointer surpasses the "right" pointer, the array is reversed in-place.

Here is an example to illustrate the process:


Initial array: [1, 2, 3, 4, 5]

Step 1: left = 0, right = 4
Swap elements at indices 0 and 4: [5, 2, 3, 4, 1]
Increment left to 1, decrement right to 3

Step 2: left = 1, right = 3
Swap elements at indices 1 and 3: [5, 4, 3, 2, 1]
Increment left to 2, decrement right to 2

Step 3: left = 2, right = 2
Since left is equal to right, no swap is needed.

The array is now reversed in-place: [5, 4, 3, 2, 1].