LeetCode: Rotate List Solution

Should draw for better imagination of how it works

Approach

Find the node for the trim to start, call this the trim list

Attach the tail of the trim list to original head

Detach the node before trim list, point its

next
to
null
, to avoid cyclic

Implementation

1var rotateRight = function (head, k) {
2 if (!head) return null
3
4 let size = 0
5 for (let iter = head; iter; iter = iter.next) size++
6
7 k %= size
8 k = size - k - 1
9
10 let tail = head
11 let beforeTrimStart = head
12
13 while (tail.next) tail = tail.next
14 while (k--) beforeTrimStart = beforeTrimStart.next
15
16 tail.next = head
17 const trimStart = beforeTrimStart.next
18 beforeTrimStart.next = null
19
20 return trimStart
21}

Implementation (break and rebuild)

1var rotateRight = function (head, k) {
2 if (!head) return null
3
4 const llistToArray = llist => {
5 let iter = llist
6 const res = []
7 while (iter) {
8 res.push(iter.val)
9 iter = iter.next
10 }
11 return res
12 }
13 const arrayToLlist = arr => {
14 let dummy = (iter = new ListNode())
15 arr.forEach(el => {
16 const node = new ListNode(el)
17 iter.next = node
18 iter = iter.next
19 })
20 return dummy.next
21 }
22
23 const arr = llistToArray(head)
24 k %= arr.length
25 k = arr.length - k
26
27 return arrayToLlist([...arr.slice(k), ...arr.slice(0, k)])
28}

Comments

Loading comments...

Tags

leetcode

linked list

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: Find Greatest Common Divisor of Array

Aug 22, 2021

Straight forward: min, max then gcd

Previous Post

LeetCode: Flatten a Multilevel Doubly Linked List

Aug 21, 2021

Naming variables is also important

HoningJS

Search Posts