FastPrepFlatten a Branched List into a Doubly Linked List
Problems/Flatten a Branched List into a Doubly Linked List

Flatten a Branched List into a Doubly Linked List

Tesla logoTesla● MediumFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interview report supplies the singly linked starting structure, one optional side branch per node, preorder flattening rule, and doubly linked result. It omits a portable node representation, bounds, null encoding, and examples; the indexed-array adapter supplies those details. The practice contract matches the report at about 88%.

A branched list contains n nodes. Node i stores values[i], may point to a next node through nextIndices[i], and may point to one side branch through branchIndices[i]. A value of -1 means that pointer is absent.

Flatten the structure in preorder: visit a node, then its entire side branch, then the node's original next chain. Convert that order into one doubly linked list.

Return one row per flattened position. Row i is [value, previousPosition, nextPosition], where missing neighbors are encoded as -1.

Function

flattenBranchedList(values: int[], nextIndices: int[], branchIndices: int[], headIndex: int) → int[][]

Examples

Example 1

values = [1,2,3,4,5]nextIndices = [1,2,-1,4,-1]branchIndices = [-1,3,-1,-1,-1]headIndex = 0return = [[1,-1,1],[2,0,2],[4,1,3],[5,2,4],[3,3,-1]]

The branch rooted at node 3 is inserted after node 1 and before its original next node 2.

Example 2

values = [7]nextIndices = [-1]branchIndices = [-1]headIndex = 0return = [[7,-1,-1]]

A single node has neither a previous nor a next flattened neighbor.

Example 3

values = [10,20,30,40]nextIndices = [1,-1,-1,-1]branchIndices = [2,-1,3,-1]headIndex = 0return = [[10,-1,1],[30,0,2],[40,1,3],[20,2,-1]]

Nested side branches are completed before traversal resumes along an original next pointer.

Constraints

  • 1 <= n <= 100000.
  • values.length = nextIndices.length = branchIndices.length = n.
  • Each pointer is -1 or a valid node index.
  • The nodes reachable from headIndex form an acyclic branched list, and every reachable node is visited exactly once.
  • -10^9 <= values[i] <= 10^9.

More Tesla problems

  • Reduce-Based Map and Filter PipelinePHONE SCREEN · Seen Sep 2026
  • Resilient Fake API ClientPHONE SCREEN · Seen Sep 2026
  • Alternate Positive and Negative ValuesONSITE INTERVIEW · Seen Aug 2026
All Tesla interview questionsSee Tesla hiring insights
Saved
class Solution {
    public int[][] flattenBranchedList(int[] values, int[] nextIndices, int[] branchIndices, int headIndex) {
        // Write your solution here.
    }
}
Checking account…