Problem · Linked List
Insert into a Sorted Circular List
Learn this problemProblem statement
A nondecreasing circular singly linked list is serialized by one finite traversal cycle, beginning at an arbitrary node. Therefore the values have at most one descending wrap edge.
Insert insertValue while preserving the circular nondecreasing order. Duplicates are allowed. Return one traversal of the resulting cycle:
- For a nonempty input, begin at the same original first node.
- For an empty input, return the one-node cycle containing
insertValue.
When more than one edge can accept the value, insert after the first such edge encountered from the serialized first node. The returned array is the finite runner representation of the circular list.
Function
insertIntoSortedCircular(cycle: int[], insertValue: int) → int[]Examples
Example 1
cycle = [3,4,1]insertValue = 2return = [3,4,1,2]The traversal wraps from 4 to 1. Inserting 2 between 1 and the original first node 3 preserves circular order.
Example 2
cycle = [1,3,4]insertValue = 2return = [1,2,3,4]The value belongs on the ordinary ascending edge from 1 to 3.
Example 3
cycle = []insertValue = 5return = [5]An empty list becomes a one-node cycle.
Constraints
0 <= cycle.length <= 200000.-10^9 <= cycle[i], insertValue <= 10^9.- The nonempty input has at most one index
ifor whichcycle[i] > cycle[(i + 1) % cycle.length].