Skip to content
CodeKruPro

Insert a value into a sorted circular linked list

Coding problemMedium-HardAsked in: Amazon, Microsoft, Zoho

A circular linked list holds integers. Going round the circle once from its smallest value, the values never decrease; then the circle wraps from the largest value back to the smallest.

You get the circle opened up at some node, which need not hold the smallest value: a linked list whose first node is that node and whose last node is the one that, in the circle, links back to the first. Insert a new node holding value at a place that keeps the circle sorted. Return the circle opened at the same starting node, so the original first node stays first.

If the circle is empty, return a list with just the new node. If several places keep the circle sorted (for example when values repeat), any of them is accepted.

Examples

Example 1
Input: head = [3,4,1], value = 2
Output: [3,4,1,2]
Round the circle the order is 1, 2, 3, 4. The new node goes between 1 and the starting node 3, so it ends up last.
Example 2
Input: head = [], value = 1
Output: [1]
Example 3
Input: head = [5,1,3], value = 6
Output: [5,6,1,3]
The largest value goes at the wrap point, between 5 and 1.

Constraints

  • The circle has between 0 and 100,000 nodes
  • Values and value are between -1,000,000,000 and 1,000,000,000
  • The values are sorted round the circle as described

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in