Kotlin Program to Cyclically Rotate Array by One

Write a Kotlin Program to cyclically rotate array clockwise by one.

Suppose you have an array

val arr = intArrayOf(10,21,32,42,51)

If we want to cyclically rotate that array clockwise by one, output should be something like –

21,32,42,51,10

We can do so as below –

  • Assume array is of size n.
  • At first, store last element of array in a variable temp.
  • Then, move all elements to right by one position i.e. move item at n-2th position to n-1th position, item at n-3th position to n-2th position etc. That means, item at ith position will shift to i+1th position.
  • After moving all elements to it’s subsequent position, replace first item with value stored in variable temp.

Kotlin program to cyclically rotate item by one –

fun main() {

   val arr = intArrayOf(10, 21, 32, 42, 51)

   println("Given array: ")
   for(element in arr) {
      print("$element ")
   }

   // Store last element in variable temp
   val temp = arr[arr.size - 1]

   // Move all element at ith position to (i+1)th position
   for (curIndex in arr.lastIndex downTo 1) {
      arr[curIndex] = arr[curIndex-1]
   }

   // Store last element at 0th position
   arr[0] = temp

   println("\nElements after cyclically rotating array by one: ")
   for(element in arr) {
      print("$element ")
   }
}

When you run above program, you will get below output –

Given array:
10 21 32 42 51
Elements after cyclically rotating array by one:
51 10 21 32 42

Time complexity: O(n), We are iterating through all the elements in array.

That’s how we can write kotlin program to cyclically rotate array by one with example.

Leave a Reply