FastPrepReverse a Linked List Sublist

Reverse a Linked List Sublist

Bloomberg LP logoBloomberg LP● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

Given the head of a singly linked list and one-indexed positions left and right, reverse the nodes from position left through position right, inclusive.

Keep all nodes outside that segment in their original order and return the list head.

Function

reverseBetween(head: ListNode, left: int, right: int) → ListNode

Examples

Example 1

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

Only positions 2 through 4 are reversed.

Example 2

head = [5]left = 1right = 1return = [5]

A one-node segment does not change the list.

Example 3

head = [1,2]left = 1right = 2return = [2,1]

Reversing the full two-node segment changes the head.

Constraints

  • 1 <= number of nodes <= 100000.
  • -10^9 <= node.val <= 10^9.
  • 1 <= left <= right <= number of nodes.
  • The input list is finite and acyclic.

More Bloomberg LP problems

See Bloomberg LP hiring insights
/**
 * Definition for singly-linked list.
 * class ListNode {
 *   int val;
 *   ListNode next;
 * }
 */
public ListNode reverseBetween(ListNode head, int left, int right) {
    // Write your code here.
}
head[1,2,3,4,5]
left2
right4
expected[1,4,3,2,5]
Checking account…