Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array

[1,2,3,4,5,6,7]

is rotated to

[5,6,7,1,2,3,4]

Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

def rotate(nums: Array[Int], k: Int) = {
  val r = k % nums.length
  reverse(nums, 0, nums.length - 1)
  reverse(nums, 0, r - 1)
  reverse(nums, r, nums.length - 1)
  nums
}

def reverse(nums: Array[Int], start: Int, end: Int): Array[Int] = {
  val diff = (end - start) / 2
  var tmp = 0
  for (i <- 0 until diff) {
    tmp = nums(start + i)
    nums(start + i) = nums(end - i)
    nums(end - i) = tmp
  }
  nums
}

/**
  * http://blog.thedigitalcatonline.com/blog/2015/05/13/99-scala-problems-16-20/#.V84U_ZMrJE5
  */
def rotate[A](n: Int, l: List[A]): List[A] = {
  val wrapn = if (l.isEmpty) 0 else n % l.length
  if (wrapn < 0) rotate(l.length + n, l)
  else l.drop(wrapn) ::: l.take(wrapn)
}

rotate(Array(1, 2, 3, 4, 5, 6, 7, 8, 9), 2)

Last updated