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

1var 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 7
2k: 3
3
4first reverse:
5 (7 6 5 4 3 2 1)
6second reverse:
7 (5 6 7) 4 3 2 1
8third 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] = temp
7 start++
8 end--
9 }
10 }
11
12 const n = nums.length
13 k %= n
14
15 rangedReverse(nums)(0, n - 1)
16 rangedReverse(nums)(0, k - 1)
17 rangedReverse(nums)(k, n - 1)
18}

Comments

Loading comments...

Tags

leetcode

array

two pointers

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Single Number

Feb 4, 2021

Count occurence of each element

Previous Post

HoningJS

Search Posts