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
Insert into Sorted Circular Linked List INPUT Sorted Circular Linked List 1 3 4 insertVal 2 head = [1,3,4] insertVal = 2 ALGORITHM STEPS 1 Handle Empty List If null, create single node pointing to itself 2 Two-Pointer Traverse curr and curr.next pointers traverse the circular list 3 Find Insert Position Case A: curr <= val <= next Case B: At max/min boundary 4 Insert New Node Create node with insertVal Link: curr-->new-->next Finding Position: 1 2 3 curr next FINAL RESULT Updated Circular Linked List 1 2 NEW 3 4 Output: [1, 2, 3, 4] OK - List Remains Sorted Circular property preserved Non-descending order Key Insight: The two-pointer approach (curr and curr.next) efficiently finds the insertion point by checking three cases: 1) Normal case: insertVal fits between curr and next. 2) Boundary case: at the max-min wrap point. 3) All same values: insert anywhere after full traversal. Time: O(n), Space: O(1). TutorialsPoint - Insert into a Sorted Circular Linked List | Two-Pointer Approach
Asked in
Facebook 25 Google 20 Amazon 15 Microsoft 12
28.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen