The blog for Design Patterns, Linux, HA and Myself!
This document presents the solution to the problem 189. Rotate Array - Leetcode.
This problem can be solved with both O(n) space complexity and O(1) space complexity. The time complexity will remain O(n) in both the cases.
Let’s first discuss the solution with O(n) space complexity. Here are steps:
temp with size equaling len(n)temp contains the same elements from numsnums array is copied to a new position in temp such that:
temp[(i + k) % n] = nums[i]i is 1 and k is 4 then nums[i] will be placed at the index 1 if the length of nums is 5.Here’s the program with O(n) space complexity:
func rotate(nums []int, k int) {
n := len(nums)
k = k % n // Handle k > n
// Create a temporary array
temp := make([]int, n)
// Place each element at its new position
for i := 0; i < n; i++ {
temp[(i+k)%n] = nums[i]
}
// Copy back to original array
copy(nums, temp)
}
Note: We’ve updated k to k % n so that we remove the unnecessary swaps. With the array size being 5, k with values 8 and 3 will have the same output.
Let’s look into the solution with O(1) space complexity.
Developing the intution
k times.k indices will be shifted to the right of the array.k elements will be moved from end to the begin. The array will be partitioned between the elements that move left and the elements moving right.Here’s the initial state:
Here’s what the final array state looks like:
The redline is the partition with k = 3 items moving from the end to the start of the array.
To reach to this state, we can reverse the array and then reverse the array slice for both the partitions:
func reverse(nums []int, i, j int) {
for i <= j {
temp := nums[i]
nums[i] = nums[j]
nums[j] = temp
i++
j--
}
}
func rotate(nums []int, k int) {
k = k % len(nums)
// reverse the array
reverse(nums, 0, len(nums)-1)
reverse(nums, k, len(nums)-1)
reverse(nums, 0, k-1)
}
Please do provide some comments if you find the explanation a bit lacking.