1580. Split at Value Drops
A sensor stores its readings in a singly linked list, and a new recording session begins whenever a reading is lower than the one just before it. Given head, cut the list immediately before every node whose value is strictly smaller than the value of the node in front of it, so that each piece is a maximal run of non-decreasing values. Equal neighbours stay together. Return the pieces as an array of list heads in their original left-to-right order; an empty list produces an empty array. The nodes are reused and only their next pointers change. Aim for one pass over the list: O(n) time and O(1) extra space beyond the returned array.
Example 1
- Input:
- head = [3,3,1,5,2,2]
- Output:
- [[3,3],[1,5],[2,2]]
- Explanation:
The values drop at 3 to 1 and at 5 to 2, giving the pieces [3,3], [1,5] and [2,2].
Example 2
- Input:
- head = [1,2,3,4]
- Output:
- [[1,2,3,4]]
- Explanation:
No value is smaller than its predecessor, so the whole list is one piece.
Example 3
- Input:
- head = [9,7,4]
- Output:
- [[9],[7],[4]]
- Explanation:
Every value drops, so each node becomes its own piece.
Constraints
0 ≤ 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)