1582. Relocate Kth to Front

Easy1.5 points estimatedLinked List

A help desk keeps tickets in a singly linked list, and a supervisor wants one particular ticket handled first. Given head and an integer k, unlink the k-th node (counting from 1 at the head) and make it the new head of the list. Every other node keeps its relative order behind it. Return the new head; when k is 1 the list is unchanged. The list always has at least k nodes. Relink the existing nodes instead of copying values, using one forward walk to the node just before the k-th one: O(n) time and O(1) extra space.

Example 1

Input:
head = [10,20,30,40], k = 3
Output:
[30,10,20,40]
Explanation:

The 3rd node (30) is unlinked and becomes the head: 30, 10, 20, 40.

Example 2

Input:
head = [5,6,7], k = 1
Output:
[5,6,7]
Explanation:

k = 1 means the head is already first, so the list is unchanged.

Example 3

Input:
head = [1,2,3,4,5], k = 5
Output:
[5,1,2,3,4]
Explanation:

The last node moves to the front, giving 5, 1, 2, 3, 4.

Constraints

1 ≤ k ≤ length ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…