# LeetCode: Rotate Array Solution

Stale solution might be time-limit exceeded someday

## Approach: Pop and Unshift

Note: this solution got TLE after a recheck in Sep 13th 2021

## Implementation

`.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var rotate = function (nums, k) {2  while (k--) {3    let temp = nums.pop()4    nums.unshift(temp)5  }6}`

## Approach: Reverse

```1nums: 1 2 3 4 5 6 72k: 33
4first reverse:5  (7 6 5 4 3 2 1)6second reverse:7  (5 6 7) 4 3 2 18third reverse:9  5 6 7 (1 2 3 4)```

## Implementation

```1var rotate = function (nums, k) {2  const rangedReverse = arr => (start, end) => {3    while (start <= end) {4      const temp = arr[start]5      arr[start] = arr[end]6      arr[end] = temp7      start++8      end--9    }10  }11
12  const n = nums.length13  k %= n14
15  rangedReverse(nums)(0, n - 1)16  rangedReverse(nums)(0, k - 1)17  rangedReverse(nums)(k, n - 1)18}```

leetcode

array

two pointers

## Next Post

LeetCode: Single Number

Feb 4, 2021

Count occurence of each element

Search Posts