FastPrepMove the Nth Linked-List Node to the Front

Move the Nth Linked-List Node to the Front

LinkedIn logoLinkedIn● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

Given the head of a nonempty singly linked list and a one-based position n, move the actual node at position n to the front and return the new head. The first node has position 1.

Change links rather than copying or swapping node values. Every other node must keep its relative order. When n = 1, return the original list unchanged. The supplied position is always valid.

Function

moveNthToFront(head: ListNode, n: int) → ListNode

Examples

Example 1

head = [1,2,3,4]n = 3return = [3,1,2,4]

Relink the selected node before the old head; every other node keeps its relative order.

Example 2

head = [8]n = 1return = [8]

Relink the selected node before the old head; every other node keeps its relative order.

Example 3

head = [5,5,7]n = 3return = [7,5,5]

Relink the selected node before the old head; every other node keeps its relative order.

Constraints

  • 1 <= number of nodes <= 100000.
  • 1 <= n <= number of nodes.
  • -10^9 <= node.val <= 10^9.
  • The list is acyclic.

More LinkedIn problems

See LinkedIn hiring insights
public ListNode moveNthToFront(ListNode head, int n) {
    // Write your code here.
}
head[1,2,3,4]
n3
expected[3,1,2,4]
Checking account…