Given an array Arr of N integers, the task is to reverse a subarray of that array. The range of this subarray is given by L and R.
Examples:
Input: arr = [1, 2, 3, 4, 5, 6, 7], L = 1, R = 5
Output: [1, 6, 5, 4, 3, 2, 7]Input: arr = [10, 20, 30, 40, 50], L = 0, R = 2
Output: [30, 20, 10, 40, 50]
Approach: Follow the steps below to solve the problem:
- If the size of the sub-list is 1, then return the array.
- If the size of the sub list is 2, then swap if the range lies between them.
- Else, Start swapping from L and R up to the mid of (L + R).
Below is the implementation of the above approach:
Python3
|
Original Array : [1, 2, 3, 4, 5, 6, 7] Sub-Array reverse : [1, 6, 5, 4, 3, 2, 7]
Time complexity: O(log2(n))
Auxiliary space: O(1)
Related articles:
Given an array Arr of N integers, the task is to reverse a subarray of that array. The range of this subarray is given by L and R.
Examples:
Input: arr = [1, 2, 3, 4, 5, 6, 7], L = 1, R = 5
Output: [1, 6, 5, 4, 3, 2, 7]Input: arr = [10, 20, 30, 40, 50], L = 0, R = 2
Output: [30, 20, 10, 40, 50]
Approach: Follow the steps below to solve the problem:
- If the size of the sub-list is 1, then return the array.
- If the size of the sub list is 2, then swap if the range lies between them.
- Else, Start swapping from L and R up to the mid of (L + R).
Below is the implementation of the above approach:
Python3
|
Original Array : [1, 2, 3, 4, 5, 6, 7] Sub-Array reverse : [1, 6, 5, 4, 3, 2, 7]
Time complexity: O(log2(n))
Auxiliary space: O(1)
Related articles: