1365. Front or Back Moves
A librarian wants the books on a shelf, labelled by the integers in nums, in non-decreasing order from left to right. A single move lifts any one book and places it at the very beginning or at the very end of the shelf.
Return the minimum number of moves needed. Books that are never moved must keep their relative order, so they form a subsequence that is non-decreasing and also covers a contiguous block of the sorted values: every book whose label lies strictly between the smallest and the largest label of this subsequence must be in it, while books that share the smallest or the largest label may or may not be. The answer is n minus the longest such subsequence. Aim for O(n log n) time and O(n) space.
Example 1
- Input:
- nums = [4,7,2,3,9]
- Output:
- 2
- Explanation:
Keep 4, 7 and 9 where they are and move 3 and then 2 to the front, giving [2, 3, 4, 7, 9] in 2 moves.
Example 2
- Input:
- nums = [1,2,3]
- Output:
- 0
- Explanation:
The shelf is already sorted, so no move is needed.
Example 3
- Input:
- nums = [2,1,2,1]
- Output:
- 2
- Explanation:
Move the 2 at index 0 to the back to get [1, 2, 1, 2], then move the 1 at index 2 to the front to get [1, 1, 2, 2], so 2 moves.
Constraints
-
1 ≤ nums.length ≤ 105 -
0 ≤ nums[i] ≤ 109
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)