DEV Community

Samantha Vincent
Samantha Vincent

Posted on

Reverse the array

Problem

You’re given an array of integers and need to reverse the array in-place.


Strategy

At first, it feels like you can just use a built-in reverse function.

But since we need to do it in-place, I thought about it differently:

What if I swap elements from both ends?

So I use two pointers:

  • One at the start
  • One at the end

Then keep swapping them and move inward.


Code

class Solution:
    def reverseArray(self, arr):
        left = 0
        right = len(arr) - 1

        while left < right:
            arr[left], arr[right] = arr[right], arr[left]
            left += 1
            right -= 1
Enter fullscreen mode Exit fullscreen mode

Key Lines Explained

arr[left], arr[right] = arr[right], arr[left]
Swaps the elements at the start and end.


left += 1 and right -= 1
Moves both pointers towards the center.


Why This Works

We’re just swapping elements from opposite ends:

  • First with last
  • Second with second last
  • And so on

By the time pointers meet, the array is reversed.


Complexity

Time: O(n)
Space: O(1)


Final Note

This is a simple two-pointer problem.

Instead of creating a new array, just swap elements in-place to reverse it efficiently.

Top comments (0)