LeetCode: Reverse Linked List II Solution

Approach

I found it hard to understand one-pass solution, so I go with the so-called cheated solution

  • Convert to linked list to array
  • Manipulate on that array
  • Convert back to linked list

Complexity

Time:

O(n)

Space:

O(n)

with

n
is the length of the list

Implementation

1/**
2 * Definition for singly-linked list.
3 * function ListNode(val, next) {
4 * this.val = (val===undefined ? 0 : val)
5 * this.next = (next===undefined ? null : next)
6 * }
7 */
8/**
9 * @param {ListNode} head
10 * @param {number} left
11 * @param {number} right
12 * @return {ListNode}
13 */
14var reverseBetween = function (head, left, right) {
15 left--
16 right--
17 const arr = []
18
19 while (head) {
20 arr.push(new ListNode(head.val))
21 head = head.next
22 }
23
24 const resArr = [
25 ...arr.slice(0, left),
26 ...arr.slice(left, right + 1).reverse(),
27 ...arr.slice(right + 1),
28 ]
29
30 for (let i = 0; i < resArr.length - 1; i++) {
31 resArr[i].next = resArr[i + 1]
32 }
33
34 return resArr[0]
35}

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: Remove All Adjacent Duplicates In String

Jun 29, 2021

Remove all adjacent and equal letters

Previous Post

HoningJS

Search Posts