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:

https://assets.leetcode.com/uploads/2019/01/19/example_1_before_65p.jpg

1
2
3
Input: head = [3,4,1], insertVal = 2
Output: [3,4,1,2]
Explanation: In the figure above, there is a sorted circular list of three elements. You are given a reference to the node with value 3, and we need to insert 2 into the list. The new node should be inserted between node 1 and node 3. After the insertion, the list should look like this, and we should still return node 3.

https://assets.leetcode.com/uploads/2019/01/19/example_1_after_65p.jpg

Example 2:

1
2
3
Input: head = [], insertVal = 1
Output: [1]
Explanation: The list is empty (given head isnull). We create a new single circular list and return the reference to that single node.

Example 3:

1
2
Input: head = [1], insertVal = 0
Output: [1,0]

Constraints:

  • 0 <= Number of Nodes <= 5 * 104
  • 106 <= Node.val, insertVal <= 106

Solution:

Scenarios possible in the list:

  1. insertVal is between two numbers in list ie insert 3 in [1,5]
  2. insertVal is smallest in list ie insert 2 in [3,4]
  3. insertVal is biggest in list ie insert 2 in [0,1]
  4. 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
"""

class Solution:
def insert(self, head: 'Node', insertVal: int) -> 'Node':
node = Node(insertVal)
if not head:
node.next = node
return node

p = head
while p:
if p.val <= insertVal <= p.next.val:
break
elif p.val > p.next.val and (insertVal <= p.next.val or insertVal >= p.val):
break
elif p.next == head:
break
p = p.next

node.next = p.next
p.next = node

return head

time complexity: $O(n)$
space complexity: $O(1)$
reference:
related problem: