DEV Community

Suruthika
Suruthika

Posted on

CA 05 - Reverse the array

Problem
Reverse Array Problem
You are given an array of integers arr[].
The goal is to reverse the array in place, without using any additional memory.

In simple terms, the last element should become the first, the second last becomes the second, and so on.

Examples
Input: [1, 4, 3, 2, 6, 5] → Output: [5, 6, 2, 3, 4, 1]
Input: [4, 5, 2] → Output: [2, 5, 4]
Input: [1] → Output: [1]

Approach

A straightforward way to think about this problem is to swap elements from both ends of the array.

Instead of creating a new reversed array, we can modify the original one by gradually moving elements into their correct positions.

Steps:
1.Start with two pointers:

  • One at the beginning (left)
  • One at the end (right)

2.Swap the elements at these positions.

3.Move the pointers inward:

  • Increment left
  • Decrement right

4.Continue this process until the two pointers meet.

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

def reverseArray(arr):
    left = 0
    right = len(arr) - 1

    while left < right:
        arr[left], arr[right] = arr[right], arr[left]
        left += 1
        right -= 1

    return arr
arr = [1, 4, 3, 2, 6, 5]
print(reverseArray(arr))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)