1571. Maximum to the Tail

Easy1.5 points estimatedLinked List

A playlist is stored as a singly linked list of loudness values, and the loudest track must be pushed to the end of the playlist. Given head, find the node with the largest value, unlink it, and reattach it as the new last node, leaving every other node in its original relative order. If several nodes share the largest value, move the earliest one only. If that node is already the last node, or the list has a single node, nothing changes. Relink the existing nodes instead of building new ones, and return the head of the resulting list (the head changes when the first node is the one that moves). The list has 1 to 1000 nodes with values between -10^9 and 10^9. Aim for O(n) time and O(1) extra space.

Example 1

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

The first 9 moves to the end, giving 2,4,9,1,9.

Example 2

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

The maximum is already the tail, so nothing changes.

Example 3

Input:
head = [7,7]
Output:
[7,7]
Explanation:

The earliest 7 moves behind the other one, which gives the same values.

Constraints

1 ≤ length ≤ 1000

-109 ≤ val ≤ 109

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…