3865. Reverse K Subarrays π
Description
You are given an integer array nums of length n and an integer k.
You must partition the array into k contiguous subarrays of equal length and reverse each subarray.
It is guaranteed that n is divisible by k.
Return the resulting array after performing the above operation.
Β
Example 1:
Input: nums = [1,2,4,3,5,6], k = 3
Output: [2,1,3,4,6,5]
Explanation:
- The array is partitioned into
k = 3subarrays:[1, 2],[4, 3], and[5, 6]. - After reversing each subarray:
[2, 1],[3, 4], and[6, 5]. - Combining them gives the final array
[2, 1, 3, 4, 6, 5].
Example 2:
Input: nums = [5,4,4,2], k = 1
Output: [2,4,4,5]
Explanation:
- The array is partitioned into
k = 1subarray:[5, 4, 4, 2]. - Reversing it produces
[2, 4, 4, 5], which is the final array.
Β
Constraints:
1 <= n == nums.length <= 10001 <= nums[i] <= 10001 <= k <= nnis divisible byk.
Solutions
Solution 1: Simulation
Since we need to partition the array into \(k\) subarrays of equal length, the length of each subarray is \(m = \frac{n}{k}\). We can use a loop to traverse the array with a step size of \(m\), and in each iteration, reverse the current subarray.
The time complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{nums}\). The space complexity is \(O(1)\), as we only use a constant amount of extra space.
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |