FastPrepFlatten a Multilevel Doubly Linked List

Flatten a Multilevel Doubly Linked List

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

A multilevel doubly linked list contains n indexed nodes. Node i stores values[i], may point to its same-level successor through nextIndices[i], and may point to the head of a child doubly linked list through childIndices[i]. A pointer value of -1 means that pointer is absent. Previous pointers are implied by each same-level next chain.

Flatten the structure in preorder: visit a node, then its complete child list, then resume at the node's original next successor. Every child pointer becomes absent, and the flattened nodes form one valid doubly linked list.

Return one row for each flattened position. Row p is [value, previousPosition, nextPosition]. Use -1 for a missing previous or next position. For an empty input, return an empty matrix.

Function

flattenMultilevelList(values: int[], nextIndices: int[], childIndices: int[], headIndex: int) → int[][]

Examples

Example 1

values = [1,2,3,4,5,6,7,8,9,10,11,12]nextIndices = [1,2,3,4,5,-1,7,8,9,-1,11,-1]childIndices = [-1,-1,6,-1,-1,-1,-1,10,-1,-1,-1,-1]headIndex = 0return = [[1,-1,1],[2,0,2],[3,1,3],[7,2,4],[8,3,5],[11,4,6],[12,5,7],[9,6,8],[10,7,9],[4,8,10],[5,9,11],[6,10,-1]]

The child chain beginning with value 7 is inserted after value 3. Its nested child chain 11, 12 is inserted after value 8 before traversal resumes at 9 and later at 4.

Example 2

values = [1,2,3]nextIndices = [1,-1,-1]childIndices = [2,-1,-1]headIndex = 0return = [[1,-1,1],[3,0,2],[2,1,-1]]

The child node with value 3 appears immediately after its parent and before the parent's original successor with value 2.

Example 3

values = []nextIndices = []childIndices = []headIndex = -1return = []

An empty multilevel list has no flattened nodes.

Constraints

  • 0 <= n <= 1000.
  • values.length = nextIndices.length = childIndices.length = n.
  • Every pointer is -1 or a valid node index.
  • If n = 0, then headIndex = -1; otherwise headIndex is valid.
  • The reachable nodes form an acyclic multilevel doubly linked structure, and every reachable node appears exactly once.
  • 1 <= values[i] <= 10^5.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int[][] flattenMultilevelList(int[] values, int[] nextIndices, int[] childIndices, int headIndex) {
    // Write your code here.
}
values[1,2,3,4,5,6,7,8,9,10,11,12]
nextIndices[1,2,3,4,5,-1,7,8,9,-1,11,-1]
childIndices[-1,-1,6,-1,-1,-1,-1,10,-1,-1,-1,-1]
headIndex0
expected[[1,-1,1],[2,0,2],[3,1,3],[7,2,4],[8,3,5],[11,4,6],[12,5,7],[9,6,8],[10,7,9],[4,8,10],[5,9,11],[6,10,-1]]
Checking account…