Insert into a sorted circular linked list
I was asked this
No reports yet. Sign in to say where you were asked it.
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—Nodehasvalandnext; returnshead, 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 andO(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
prevandcurr = prev.nextand 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
nextis 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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
