Open In App

Python | Reverse an array upto a given position

Last Updated : 15 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] and a position in array, k. Write a function name reverse (a[], k) such that it reverses subarray arr[0..k-1]. The extra space used should be O(1) and the time complexity should be O(k).

Example

Input: arr[] = {1, 2, 3, 4, 5, 6}, k = 4
Output:  arr[] = {4, 3, 2, 1, 5, 6}
The extra

Python Reverse an Array Upto a Given Position

Below are the ways by which we can reverse an array up to a given position in Python:

  • Using Slicing
  • Using Two Pointers
  • Using numpy.flip()

Reverse an Array Upto a Given range using Slicing

In this example, we are using Python Slicing to reverse an array up to a given position. This problem has an existing solution please refer to Reverse an array upto a given position link. We will solve this problem quickly in Python.

Python3




def reverseArrayUptoK(input, k):
    print (input[k-1::-1] + input[k:])
 
# Driver program
if __name__ == "__main__":
    input = [1, 2, 3, 4, 5, 6]
    k = 4
    reverseArrayUptoK(input, k)


Output

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

Python Reverse an Array Using Two Pointers

In this example, we are using two pointers to reverse an array. In this we are reversing an array upto a given position uses two pointers to swap the elements of the array. 

Python3




def reverseArray(arr, k):
  start = 0
  end = k-1
  while start < end:
    arr[start], arr[end] = arr[end], arr[start]
    start += 1
    end -= 1
  return arr
arr=[1, 2, 3, 4, 5, 6]
k = 4
print(reverseArray(arr, k))


Output

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

Time complexity: O(k/2)
Auxiliary Space: O(1)

Reverse an Array Upto a Given Position using NumPy

In this example, we are using numpy.flip() to reverse an array up to a given position. Using flip() function we can reverse the subarray arr without using any loops. We first create a array from the given input array, and then we use the flip() function to reverse the subarray up to the k-1 position. We then convert the NumPy array back to a Python list and return it.

Python3




import numpy as np
 
# function to reverse array upto given position
def reverseArrayUptoK(arr, k):
     
    # reverse subarray upto position k
    arr[0:k] = np.flip(arr[0:k], axis=0)
     
    return arr
 
# driver code
if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5, 6]
    k = 4
    print(reverseArrayUptoK(arr, k))


Output

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

Time Complexity: O(k)
Auxiliary Space: O(n)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads