Skip to content
Related Articles

Related Articles

Improve Article
Python | Reverse an array upto a given position
  • Last Updated : 21 Nov, 2018

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]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :