CA 05 - Reverse the array
Array Reverse
Reverse an array arr[]. Reversing an array means rearranging the elements such that the first element becomes the last, the second element becomes second last and so on.
Input: arr[] = [1, 4, 3, 2, 6, 5]
Output: [5, 6, 2, 3, 4, 1]
Explanation: The first element 1 moves to last position, the second element 4 moves to second-last and so on.
Input: arr[] = [4, 5, 1, 2]
Output: [2, 1, 5, 4]
Explanation: The first element 4 moves to last position, the second element 5 moves to second last and so on.
CODE:
BRUTE FORCE METHOD:
Here, in this method we will create a temporary array to store the reversed given array and then assign it to the given array
class Solution:
def reverseArray(arr):
n = len(arr)
temp = [0] * n
for i in range(n-1,-1,-1):
temp[i] = arr[i]
for i in range(n):
arr[i] = temp[i]
OPTIMIZED METHOD: Here, in optimized method the two-pointer technique is used. The left pointer is pointed to the left-most element and the right pointer is pointed to the right-most element of the array. At each step the left and right pointed elements are swapped this is done until the left does not cross the right (i.e is till the middle of the array. The space complexity is reduced as there are no extra temporary array used.
class Solution:
def reverseArray(arr):
l = 0
r = len(arr) - 1
while l < r:
arr[l], arr[r] = arr[r], arr[l]
l += 1
r -= 1
Comments
Post a Comment