MuhammadTausif / gfg-excercises

This repo is about exercises at GFG
Apache License 2.0
0 stars 0 forks source link

Reverse an Array - POTD | 17-Nov-2024 #78

Closed MuhammadTausif closed 2 hours ago

MuhammadTausif commented 2 hours ago

Reverse an Array

Link

Difficulty: Easy

You are given an array of integers arr[]. Your task is to reverse the given array.

Examples:

Input: arr = [1, 4, 3, 2, 6, 5]
Output: [5, 6, 2, 3, 4, 1]
Explanation: The elements of the array are 1 4 3 2 6 5. After reversing the array, the first element goes to the last position, the second element goes to the second last position and so on. Hence, the answer is 5 6 2 3 4 1.
Input: arr = [4, 5, 2]
Output: [2, 5, 4]
Explanation: The elements of the array are 4 5 2. The reversed array will be 2 5 4.
Input: arr = [1]
Output: [1]
Explanation: The array has only single element, hence the reversed array is same as the original.

Constraints:

MuhammadTausif commented 2 hours ago

Solved

class Solution:
    def reverseArray(self, arr):
        n=len(arr)
        l=0
        r=n-1
        while (l<=r):
            arr[l],arr[r]=arr[r],arr[l]
            l+=1
            r-=1
        return arr