4. Rotate Array by K Steps
Problem Statement
Given an array of integers and a number k, rotate the array to the right by k steps. After rotation, each element should shift to its new position, and elements that move past the end should wrap around to the beginning.
Solution (Kotlin)
fun main() {
val arr = arrayOf(12, 35, 1, 10, 34, 1)
val kInput = 3
val n = arr.size
val k = kInput % n // handle cases where k > n
if (k == 0) {
println(arr.joinToString())
return
}
val rotated = arrayListOf()
// Add last k elements
for (i in n - k until n) {
rotated.add(arr[i])
}
// Add remaining elements
for (i in 0 until n - k) {
rotated.add(arr[i])
}
println(rotated.joinToString())
}
Explanation
To rotate the array by k steps, we logically split the array into two parts:
- Part 1: The last k elements, which will move to the front
- Part 2: The first n - k elements, which will follow after
By taking the last k elements first and then appending the remaining elements,
we construct the rotated array in O(n) time.
The operation k % n ensures the rotation works even if k
is larger than the array size (e.g., rotating 10 steps in a size-6 array is same as rotating 4 steps).
The final rotated array is printed as output.