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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry Skilled in Big Data technologies, Data Structures, Algorithm, Software Development, App Development, Databases, Python, Java, C, and WordPress

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.