← Uber bank

Uber · Question 20 · Linked Lists

Flatten a multilevel doubly linked list

Linked ListsPythoncode⏱ O(n)💾 O(n)
Product-based

Problem

Flatten a multilevel doubly linked list into a single-level list.

Approach

Use DFS or stack to handle child pointers.

Time O(n)Space O(n)

How it works

  1. 1Walk the top level, splicing each child list inline.
  2. 2Stash the interrupted next link on a stack.
  3. 3Pop stashed links when a level ends; fix prev pointers.

Sample input / output

Input:
3
1 2 3
2
7 8
Output:
[1, 2, 7, 8, 3]

Constraints

0 <= nodes <= 1000; 1 <= Node.val <= 10^5; at most 50 total nodes overall.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 4Branches 4Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesnoyesno↻ repeat↻ repeat↻ repeat↻ repeatSTARTheadif not headRETURN headstack = []current = headwhile currentif current.childif current.nextstack.append(current.next)current.next =current.childcurrent.child.prev =currentcurrent.child = Noneif not current.nextand stackcurrent.next = stack.pop()current.next.prev = currentcurrent = current.nextRETURN headCLASS DNodeDEFINE __init__(self,val=0, prev=None,next=None, child=None)self.val = valself.prev = prevself.next = nextself.child = childDEFINE to_vals(head)out = []while headout.append(head.val)head = head.nextRETURN outDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it))top_vals = [int(next(it))for _ in range(n)]m = int(next(it))child_vals = [int(next(it))for _ in range(m)]top = [DNode(v) for v intop_vals]for a, b in zip(top,top[1:])a.next = bb.prev = achild = [DNode(v) for v inchild_vals]for a, b in zip(child,child[1:])a.next = bb.prev = a
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/46

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits