Python | Reverse an array upto a given position
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]. Extra space used should be O(1) and time complexity should be O(k).
Examples:
Input: arr[] = {1, 2, 3, 4, 5, 6} k = 4 Output: arr[] = {4, 3, 2, 1, 5, 6}
This problem has existing solution please refer Reverse an array upto a given position link. We will solve this problem quickly in Python.
# Program to Reverse an array # upto a given position def reverseArrayUptoK( input , k): # reverse list starting from k-1 position # and split remaining list after k # concat both parts and print # input[k-1::-1] --> generate list starting # from k-1 position element till first # element in reverse order 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]