DEV Community

Dharani
Dharani

Posted on

Reverse The Array

Introduction

Reversing an array is one of the basic problems in programming. It helps us understand indexing, loops, and array manipulation.


Problem Statement

Given an array of elements, reverse the array so that the first element becomes the last and the last becomes the first.


Approach

We can solve this problem using two-pointer technique:

  1. Initialize two pointers:
    • One at the beginning (left)
    • One at the end (right)
  2. Swap the elements at both positions
  3. Move left pointer forward and right pointer backward
  4. Repeat until left < right

Python Code


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

    while left < right:
        # Swap elements
        arr[left], arr[right] = arr[right], arr[left]

        left += 1
        right -= 1

    return arr

## Example: 
Input
 [1, 2, 3, 4, 5]
ouput
[5,4,3,2,1]


Enter fullscreen mode Exit fullscreen mode

Top comments (0)