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) |
chevron_right
filter_none
Output:
[4, 3, 2, 1, 5, 6]
Recommended Posts:
- Python | Reverse a numpy array
- Python Slicing | Reverse an array in groups of given size
- Python | Padding a string upto fixed length
- Python | Find fibonacci series upto n using lambda
- Python | Position Summation in List of Tuples
- Python Slicing | Extract ‘k’ bits from a given position
- Python | Add element at alternate position in list
- Python | Selective Merge list every Nth position
- Python | Shift last element to first position in list
- Python | Find position of a character in given string
- Python | Maximum and minimum element's position in a list
- Python | Find frequency of given character at every position in list of lists
- Python list | reverse()
- Python | Reverse Slicing of given string
- Python | Reverse each word in a sentence
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.