Skip to main content

69. Reverse Linked List II

mediumAsked at Ola

Reverse a linked list between positions left and right.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right and return the reversed list.

Constraints

  • Number of nodes is n
  • 1 <= n <= 500
  • 1 <= left <= right <= n

Examples

Example 1

Input
head = [1,2,3,4,5], left = 2, right = 4
Output
[1,4,3,2,5]

Example 2

Input
head = [5], left = 1, right = 1
Output
[5]

Approaches

1. Collect into array

Read values, reverse a slice, write back.

Time
O(n)
Space
O(n)
const arr=[]; let n=head; while(n){arr.push(n.val); n=n.next;}
let l=left-1, r=right-1; while(l<r){[arr[l],arr[r]]=[arr[r],arr[l]]; l++; r--;}
// write back arr to head node values

Tradeoff:

2. Iterative head-insertion

Move to position left-1, then iteratively pop the next node and insert it after prev. O(n) one pass.

Time
O(n)
Space
O(1)
function reverseBetween(head, left, right) {
  const dummy = { next: head };
  let prev = dummy;
  for (let i = 1; i < left; i++) prev = prev.next;
  const start = prev.next;
  for (let i = 0; i < right - left; i++) {
    const mv = start.next;
    start.next = mv.next;
    mv.next = prev.next;
    prev.next = mv;
  }
  return dummy.next;
}

Tradeoff:

Ola-specific tips

Ola uses this to test surgical pointer flips; tie it to reordering a contiguous slice of dispatch hops without affecting surrounding chain.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Reverse Linked List II and other Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →