← Questions

Insert into a sorted circular linked list

0
MetaCodingLast asked Dec 2025

A coding interview question asked in Meta's AI-enabled coding round, last asked Dec 2025. It tests linked lists.

You get a reference to some node of a circular singly linked list whose values are sorted in nondecreasing order around the cycle. The node you get is not necessarily the smallest. Insert a new value so the list stays sorted around the cycle, and return a node of the list. If the list is empty, create a one-node cycle.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • insert(head: Node | None, value: int) -> Node — Node has val and next; returns head, or the new node if the list was empty.

Example

Lists are written as the values met when walking once around the cycle from head. The result is shown starting at a smallest value.

head -> 3 -> 4 -> 1 -> (back to 3),  value = 2   ->  1, 2, 3, 4
head -> 2 -> 2 -> 2 -> (back),       value = 2   ->  2, 2, 2, 2
head -> 3 -> 5 -> 1 -> (back),       value = 0   ->  0, 1, 3, 5     # smaller than everything
head -> 3 -> 5 -> 1 -> (back),       value = 6   ->  1, 3, 5, 6     # larger than everything
empty list,                          value = 1   ->  1              # one node pointing to itself

Constraints

  • 0 <= number of nodes <= 10^5; values are 32-bit integers and may repeat.
  • O(n) time and O(1) extra space.

Clarifying questions

  • Can the list be empty?
  • Can values repeat, or all be equal?
  • Which node should be returned?
  • Is the head guaranteed to be the minimum? (No.)

What a strong answer covers

  • Walk with prev and curr = prev.next and insert between them in one of three cases: prev.val <= value <= curr.val (an ordinary gap); prev.val > curr.val (the wrap point from max to min) and the value is at least the max or at most the min; or you have gone all the way round without finding a place (all values equal), in which case anywhere works.
  • Stopping after one full loop, so an all-equal list does not loop forever.
  • The empty list: a new node whose next is itself.
  • O(n) time, O(1) space.
  • Tests: empty list, one node, all equal values, a new minimum, a new maximum, duplicates of the inserted value, a head in the middle of the order.

Follow-ups

  • Delete a value from the same kind of list.
  • Insert many values at once efficiently.
  • Return the node holding the smallest value in O(n) without extra memory.

Where it's asked

  • Meta · AI-enabled coding · Last asked Dec 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it

What it tests

linked lists

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding