708. Insert into a Sorted Circular Linked List
Problem description:
Given a Circular Linked List node, which is sorted in ascending 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.
Example 1:
1 | Input: head = [3,4,1], insertVal = 2 |
Example 2:
1 | Input: head = [], insertVal = 1 |
Example 3:
1 | Input: head = [1], insertVal = 0 |
Constraints:
0 <= Number of Nodes <= 5 * 104
106 <= Node.val, insertVal <= 106
Solution:
Scenarios possible in the list:
- insertVal is between two numbers in list ie insert 3 in [1,5]
- insertVal is smallest in list ie insert 2 in [3,4]
- insertVal is biggest in list ie insert 2 in [0,1]
- array has same values ie insert 2 in [3,3,3] or insert 4 in [3,3,3,3]. Once we find list has same numbers, we can insertVal in between any two numbers which will sufficee.
Lets look how each if
condition above, handles specific scenario:
if node.next.val < node.val and (insertVal <= node.next.val or insertVal >= node.val):
-> Scenarios b) and c)
if node.val <= insertVal <= node.next.val
-> Scenario a)
if node.next == head
-> Scenario d)
1 | """ |
time complexity: $O(n)$
space complexity: $O(1)$
reference:
related problem: