Smallest Turn
One turn takes the first node of the list and puts it at the end. Turning a list of n nodes 0, 1, 2, up to n - 1 times gives n lists.
Return the smallest of them. Two lists are compared item by item from the front, and the first place where they differ decides: the list with the smaller value there is the smaller list. For 3 -> 1 -> 2 the turns give 3, 1, 2 and 1, 2, 3 and 2, 3, 1, so the answer is 1 -> 2 -> 3. The list is passed in as head.
Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.
Example 1
One turn brings the 1 to the front, and no other turn starts with a smaller value.
Example 2
Three turns start with 1. Of those, 1, 1, 2, 1, 2 is smallest: it has a 1 in second place.
Example 3
The list is smallest as it is.
Constraints
0 <= number of nodes <= 60-100 <= node.val <= 100
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Linked lists problems
- Subtract Two NumbersHard
- Swap Neighboring BlocksHard
- Alternating SumBeginner
- Are the Lists EqualBeginner
- Average of the ValuesBeginner
- Balanced Open and CloseBeginner
- Binary Linked List to IntegerBeginner
- Build a Linked List From an ArrayBeginner