Insert into a Sorted Circular Linked List - Problem
Given a Circular Linked List node, which is sorted in non-descending order, write a function to insert a value insertVal into the list such that it remains a sorted circular list.
The given node can be a reference to any single node in the list and may not necessarily be the smallest value in the circular list.
If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the circular list should remain sorted.
If the list is empty (i.e., the given node is null), you should create a new single circular list and return the reference to that single node. Otherwise, you should return the originally given node.
Input & Output
Example 1 — Normal Insertion
$
Input:
head = [1,3,4], insertVal = 2
›
Output:
[1,2,3,4]
💡 Note:
Insert 2 between 1 and 3 to maintain sorted order. The circular structure is preserved with the last node pointing back to the first.
Example 2 — Empty List
$
Input:
head = [], insertVal = 1
›
Output:
[1]
💡 Note:
Empty list case: Create a new single-node circular list where the node points to itself.
Example 3 — Insert at Boundary
$
Input:
head = [3,4,1], insertVal = 2
›
Output:
[3,4,1,2]
💡 Note:
Insert 2 at the wrap-around point between 4 and 1, since 2 fits between the maximum (4) and minimum (1) values.
Constraints
- 0 ≤ Number of Nodes ≤ 5 × 104
- -106 ≤ Node.val ≤ 106
- -106 ≤ insertVal ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input
Circular linked list [1,3,4] and insertVal = 2
2
Process
Find correct position between 1 and 3
3
Output
Resulting circular list [1,2,3,4]
Key Takeaway
🎯 Key Insight: In a sorted circular list, there's exactly one transition point from maximum to minimum value where boundary insertions occur
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code