Originally published byDev.to
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:
- Initialize two pointers:
- One at the beginning (left)
- One at the end (right)
- Swap the elements at both positions
- Move left pointer forward and right pointer backward
- 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]
πΊπΈ
More news from United StatesUnited States
NORTH AMERICA
Related News
CBS News Shutters Radio Service After Nearly a Century
5h ago
White House Unveils National AI Policy Framework To Limit State Power
5h ago
Officer Leaks Location of French Aircraft Carrier With Strava Run
5h ago
Microsoft Says It Is Fixing Windows 11
5h ago
NASA's Hubble Unexpectedly Catches Comet Breaking Up
5h ago