Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to reverse an array up to a given position in Python
In this tutorial, we will learn how to reverse an array up to a given position. This means reversing elements from index 0 to index (n-1), while keeping the remaining elements in their original positions.
Problem Statement
Given an array of integers and a number n, reverse the elements from the 0th index to (n-1)th index ?
Input: array = [1, 2, 3, 4, 5, 6, 7, 8, 9], n = 5 Output: [5, 4, 3, 2, 1, 6, 7, 8, 9]
Method 1: Using Swapping
This approach swaps elements from both ends of the subarray until we reach the middle ?
# initializing array and a number
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 5
# checking whether the n value is less than length of the array or not
if n > len(arr):
print(f"{n} value is not valid")
else:
# loop until n // 2
for i in range(n // 2):
arr[i], arr[n - i - 1] = arr[n - i - 1], arr[i]
# printing the array
print(arr)
[5, 4, 3, 2, 1, 6, 7, 8, 9]
Method 2: Using Slicing
Python slicing provides a more concise way to reverse the subarray ?
# initializing array and a number
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 5
# checking whether the n value is less than length of the array or not
if n > len(arr):
print(f"{n} value is not valid")
else:
# reversing the arr up to n
# [n-1::-1] reverses from index (n-1) to 0
# [n:] keeps elements from index n to end unchanged
arr = arr[n-1::-1] + arr[n:]
# printing the array
print(arr)
[5, 4, 3, 2, 1, 6, 7, 8, 9]
How It Works
For the input array [1, 2, 3, 4, 5, 6, 7, 8, 9] with n = 5:
- Method 1: Swaps elements at positions (0,4), (1,3) while position 2 stays the same
-
Method 2:
arr[4::-1]gives[5, 4, 3, 2, 1]andarr[5:]gives[6, 7, 8, 9]
Comparison
| Method | Space Complexity | Readability | Modifies Original |
|---|---|---|---|
| Swapping | O(1) | Good | Yes |
| Slicing | O(n) | Excellent | No (creates new array) |
Conclusion
Use the swapping method for in-place reversal with minimal memory usage. Use slicing for cleaner, more readable code when memory isn't a constraint.
Advertisements
