KatInterview

850. Insert into a Sorted Circular Linked List

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to insert a new value insertVal into a sorted circular linked list, ensuring the list remains sorted and circular after the insertion. The given head can point to any node in the list, not necessarily the minimum element. We need to handle several cases, including an empty list, a single-node list, and lists where all elements are the same.

Solution

Insert into a Sorted Circular Linked List in Python

"""
# 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: 'Optional[Node]', insertVal: int) -> 'Node':
        newNode = Node(insertVal)

        # Case 1: The list is empty.
        if not head:
            newNode.next = newNode  # Points to itself to make it circular
            return newNode

        prev, curr = head, head.next

        # Use a do-while equivalent to traverse the list.
        # The loop condition is checked at the end of the first iteration.
        while True:
            # Case 2: Found the insertion spot in a sorted segment.
            # insertVal is between prev and curr.
            if prev.val <= insertVal <= curr.val:
                break

            # Case 3: Found the wrap-around point (max element -> min element).
            if prev.val > curr.val:
                # insertVal is the new max or new min.
                if insertVal >= prev.val or insertVal <= curr.val:
                    break
            
            prev, curr = curr, curr.next
            # Break if we've completed a full circle. This handles lists with uniform values.
            if prev == head:
                break

        # After the loop, `prev` and `curr` define the insertion point.
        prev.next = newNode
        newNode.next = curr

        return head

Insert into a Sorted Circular Linked List in Java

/*
// Definition for a Node.
class Node {
    public int val;
    public Node next;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _next) {
        val = _val;
        next = _next;
    }
};
*/

class Solution {
    public Node insert(Node head, int insertVal) {
        Node newNode = new Node(insertVal);

        // Case 1: The list is empty.
        if (head == null) {
            newNode.next = newNode; // Points to itself to make it circular
            return newNode;
        }

        Node prev = head;
        Node curr = head.next;

        // Use a do-while loop to traverse the list.
        // This handles single-node lists correctly.
        do {
            // Case 2: Found the insertion spot in a sorted segment.
            // insertVal is between prev and curr.
            if (prev.val <= insertVal && insertVal <= curr.val) {
                break;
            }

            // Case 3: Found the wrap-around point (max element -> min element).
            if (prev.val > curr.val) {
                // insertVal is the new max or new min.
                if (insertVal >= prev.val || insertVal <= curr.val) {
                    break;
                }
            }
            
            prev = curr;
            curr = curr.next;
        } while (prev != head);

        // After the loop, `prev` and `curr` define the insertion point.
        // This works for the cases where we broke the loop, and also for the case
        // where the loop completed (all elements are the same).
        prev.next = newNode;
        newNode.next = curr;

        return head;
    }
}

Insert into a Sorted Circular Linked List in C++

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;

    Node() {}

    Node(int _val) {
        val = _val;
        next = NULL;
    }

    Node(int _val, Node* _next) {
        val = _val;
        next = _next;
    }
};
*/

class Solution {
public:
    Node* insert(Node* head, int insertVal) {
        Node* newNode = new Node(insertVal);

        // Case 1: The list is empty.
        if (head == nullptr) {
            newNode->next = newNode; // Points to itself to make it circular
            return newNode;
        }

        Node* prev = head;
        Node* curr = head->next;

        // Use a do-while loop to traverse the list.
        // This handles single-node lists correctly.
        do {
            // Case 2: Found the insertion spot in a sorted segment.
            // insertVal is between prev and curr.
            if (prev->val <= insertVal && insertVal <= curr->val) {
                break;
            }

            // Case 3: Found the wrap-around point (max element -> min element).
            if (prev->val > curr->val) {
                // insertVal is the new max or new min.
                if (insertVal >= prev->val || insertVal <= curr->val) {
                    break;
                }
            }
            
            prev = curr;
            curr = curr->next;
        } while (prev != head);

        // After the loop, `prev` and `curr` define the insertion point.
        // This works for the cases where we broke the loop, and also for the case
        // where the loop completed (all elements are the same).
        prev->next = newNode;
        newNode->next = curr;

        return head;
    }
};

Insert into a Sorted Circular Linked List in TypeScript

/**
 * Definition for _Node.
 * class _Node {
 *     val: number
 *     next: _Node | null
 *     
 *     constructor(val?: number, next?: _Node) {
 *         this.val = (val===undefined ? 0 : val);
 *         this.next = (next===undefined ? null : next);
 *     }
 * }
 */


function insert(head: _Node | null, insertVal: number): _Node | null {
    const newNode = new _Node(insertVal);

    // Case 1: The list is empty.
    if (!head) {
        newNode.next = newNode; // Points to itself to make it circular
        return newNode;
    }

    let prev = head;
    let curr = head.next;

    // Use a do-while loop to traverse the list.
    // This handles single-node lists correctly.
    do {
        // Case 2: Found the insertion spot in a sorted segment.
        // insertVal is between prev and curr.
        if (prev.val <= insertVal && insertVal <= curr.val) {
            break;
        }

        // Case 3: Found the wrap-around point (max element -> min element).
        if (prev.val > curr.val) {
            // insertVal is the new max or new min.
            if (insertVal >= prev.val || insertVal <= curr.val) {
                break;
            }
        }
        
        prev = curr;
        curr = curr.next;
    } while (prev !== head);

    // After the loop, `prev` and `curr` define the insertion point.
    // This works for the cases where we broke the loop, and also for the case
    // where the loop completed (all elements are the same).
    prev.next = newNode;
    newNode.next = curr;

    return head;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.