Forem

ARUL SELVI ML
ARUL SELVI ML

Posted on

Reverse the array

Reverse an Array

Reversing an array means rearranging the elements such that the first element becomes the last, the second element becomes the second last, and so on.


Problem Statement

Given an array, reverse its elements.


Example 1

Input
arr = [1, 4, 3, 2, 6, 5]

Output
[5, 6, 2, 3, 4, 1]


Example 2

Input
arr = [4, 5, 1, 2]

Output
[2, 1, 5, 4]


Approach 1 Using Two Pointers

In this method, we swap elements from the beginning and end moving towards the center.

Steps

  • Start one pointer at the beginning
  • Start another pointer at the end
  • Swap both elements
  • Move the first pointer forward
  • Move the second pointer backward
  • Continue until both pointers meet

Code

```python id="rev1"
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
Enter fullscreen mode Exit fullscreen mode



---

## Approach 2 Using Built in Method

Python provides a simple way to reverse an array.



```python id="rev2"
def reverseArray(arr):
    return arr[::-1]
Enter fullscreen mode Exit fullscreen mode

Approach 3 Using Reverse Function

```python id="rev3"
def reverseArray(arr):
arr.reverse()
return arr




---

## Explanation

Reversing works by swapping elements from opposite ends. The first element goes to the last position, the second to the second last, and this continues until the middle is reached.

---

## Conclusion

Reversing an array is a basic problem that helps in understanding indexing and element swapping. It is commonly used in many algorithms and coding interviews.

Practice different methods to become comfortable with array manipulation.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)