DEV Community

Discussion on: Is JavaScript's .shift() Method a Performance Boost?

Collapse
 
sh4bbi profile image
Shahnawaz Ansari • Edited

For rotating an array of length n by k places, the trick is to

  1. reverse the whole array first,
  2. reverse the first n - k elements,
  3. and then reverse the last k elements
function reverse(arr, start, end) {
    for (; start < end; start++, end--) {
        let temp = arr[start]
        arr[start] = arr[end]
        arr[end] = temp
    }
}

function rotateLeft(arr, k) {
    let n = arr.length
    reverse(arr, 0, n - 1)
    reverse(arr, 0, n - k - 1)
    reverse(arr, n - k, n - 1)
}
Enter fullscreen mode Exit fullscreen mode