Rotate Array

  • May 10, 2022

An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place.

The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.

Let’s write an efficient algorithm for the following assumptions:

  • N and K are integers within the range [0..100];
  • each element of array A is an integer within the range [−1,000..1,000].

1
2
3
4
5
6
    Input: nums = [1,2,3,4,5,6,7], k = 3
    Output: [5,6,7,1,2,3,4]
    Explanation:
    rotate 1 steps to the right: [7,1,2,3,4,5,6]
    rotate 2 steps to the right: [6,7,1,2,3,4,5]
    rotate 3 steps to the right: [5,6,7,1,2,3,4]

1
2
3
4
5
    Input: nums = [-1,-100,3,99], k = 2
    Output: [3,99,-1,-100]
    Explanation: 
    rotate 1 steps to the right: [99,-1,-100,3]
    rotate 2 steps to the right: [3,99,-1,-100]

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class CyclicRotation {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            var intArray = intArrayOf(3, 8, 9, 7, 6)
            println("solution: \${solution(intArray, 3).contentToString()}")
            intArray = intArrayOf(0,0,0)
            println("solution: \${solution(intArray, 1).contentToString()}")
            intArray = intArrayOf(1,2,3,4)
            println("solution: \${solution(intArray, 4).contentToString()}")
        }

        fun solution(A: IntArray, K: Int): IntArray {
            var i = 0
            val size = A.size
            println("input Array: \${A.contentToString()}")
            val tempArray = IntArray(size)
            var resultArray = A
            while (i < K) {
                for ((index, value) in resultArray.withIndex()) {
                    if (index == (size-1)) {
                        tempArray[0] = value
                    }
                    else {
                        tempArray[index+1] = value
                    }
                }
                resultArray = tempArray.clone()
                i++
            }
            return resultArray
        }
    }
}
comments powered by Disqus

Related Posts

Binary Gap

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

Read More