Problem · Linked List

Insert into a Sorted Circular List

Learn this problem
MediumMeta logoMetaFULLTIMEONSITE INTERVIEW
See Meta hiring insights

Problem statement

A nondecreasing circular singly linked list is serialized by one finite traversal cycle, beginning at an arbitrary node. Therefore the values have at most one descending wrap edge.

Insert insertValue while preserving the circular nondecreasing order. Duplicates are allowed. Return one traversal of the resulting cycle:

  • For a nonempty input, begin at the same original first node.
  • For an empty input, return the one-node cycle containing insertValue.

When more than one edge can accept the value, insert after the first such edge encountered from the serialized first node. The returned array is the finite runner representation of the circular list.

Function

insertIntoSortedCircular(cycle: int[], insertValue: int) → int[]

Examples

Example 1

cycle = [3,4,1]insertValue = 2return = [3,4,1,2]

The traversal wraps from 4 to 1. Inserting 2 between 1 and the original first node 3 preserves circular order.

Example 2

cycle = [1,3,4]insertValue = 2return = [1,2,3,4]

The value belongs on the ordinary ascending edge from 1 to 3.

Example 3

cycle = []insertValue = 5return = [5]

An empty list becomes a one-node cycle.

Constraints

  • 0 <= cycle.length <= 200000.
  • -10^9 <= cycle[i], insertValue <= 10^9.
  • The nonempty input has at most one index i for which cycle[i] > cycle[(i + 1) % cycle.length].

More Meta problems

drafts saved locally
public int[] insertIntoSortedCircular(int[] cycle, int insertValue) {
    // Write your code here.
}
cycle[3,4,1]
insertValue2
expected[3,4,1,2]
checking account