Insert into a Sorted Circular List — Pointer Scan

Sanjeev SharmaSanjeev Sharma
2 min read

Advertisement

Problem 240 · Insert into a Sorted Circular List

Difficulty: Medium · Pattern: Circular List Pointer Scan

Cases to Handle

  1. Normal: find where cur.val ≤ val ≤ cur.next.val
  2. Wraparound: cur.val > cur.next.val (at the seam) and val is max or min
  3. Full traversal without match: all equal, insert anywhere

Solutions

# Python
def insert(head, insertVal):
    node = Node(insertVal)
    if not head: node.next = node; return node
    cur = head
    while True:
        if cur.val <= insertVal <= cur.next.val:
            break
        if cur.val > cur.next.val:  # at seam
            if insertVal >= cur.val or insertVal <= cur.next.val:
                break
        if cur.next == head:  # full loop
            break
        cur = cur.next
    node.next = cur.next; cur.next = node
    return head
// Java
public Node insert(Node head, int insertVal) {
    Node node = new Node(insertVal);
    if (head == null) { node.next = node; return node; }
    Node cur = head;
    while (true) {
        if (cur.val <= insertVal && insertVal <= cur.next.val) break;
        if (cur.val > cur.next.val && (insertVal >= cur.val || insertVal <= cur.next.val)) break;
        if (cur.next == head) break;
        cur = cur.next;
    }
    node.next = cur.next; cur.next = node;
    return head;
}

Complexity

  • Time: O(n)
  • Space: O(1)

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro