Codiwan.com

The blog for Design Patterns, Linux, HA and Myself!

Rotate Array Solution - Leetcode

Understand Rotate Array (189 Leetcode) with Solution

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:

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

  1. The array elements will be shifted to the right for k times.
  2. The elements present at the last k indices will be shifted to the right of the array.
  3. So, we are moving the last set of items to the beginning and the first set of items to the end of the array.
  4. This is reversal of the array, kind of.
  5. Also, only the last 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:

initial state

Here’s what the final array state looks like:

Final state

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:

Steps
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.

Loading Comments... Disqus Loader
comments powered by Disqus