1612. Ends Moves to Sort

Hard7.5 points estimatedLinked ListGreedySorting

A librarian arranges distinct catalogue numbers stored in the singly linked list head. In one move she may unlink any single node and re-attach it either at the very front or at the very back of the list. Return the minimum number of moves needed to leave the list in increasing order. The nodes she never touches keep their relative order, so they must form a block of consecutive ranks (positions in the sorted order) that already appears in increasing order along the list; every other node is moved once to the front or the back. Return n minus the longest such block, where n is the length. All values are distinct, the list has 1 to 100000 nodes, and the target is O(n log n) time with O(n) extra space.

Example 1

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

The nodes 1, 2, 3 are consecutive ranks already in order, so only 4 and 5 move, each to the back, in 2 moves.

Example 2

Input:
head = [1,2,3]
Output:
0
Explanation:

The list is sorted, so no move is needed.

Example 3

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

Only one node can stay, so two moves are required.

Constraints

1 ≤ length ≤ 105

all values are distinct

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n log n)
Space
O(n)

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…