Reverse K Subarrays Problem
#3865
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3865.
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 = 3 subarrays: [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 = 1 subarray: [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.
Solution
Approach: Simulation
Each of the k pieces has length m = n / k. Walk through the array in steps of m and reverse each piece in place with two pointers.
Complexity: O(n) time and O(1) extra space.
class Solution:
def reverseSubarrays(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
m = n // k
for i in range(0, n, m):
nums[i : i + m] = nums[i : i + m][::-1]
return nums