Problem · Array
Recursive Display Sort
Learn this problemProblem statement
You are given n display nodes through parallel arrays. Node i has identifier ids[i], parent index parents[i], horizontal coordinate x[i], and inclusive vertical interval [top[i], bottom[i]]. A parent index of -1 marks a root.
Sort each sibling list independently:
- Place siblings in the same group when their vertical intervals overlap directly or transitively.
- Order groups from top to bottom by their minimum
topcoordinate. - Within a group, order nodes by increasing
x, then increasingtop, then original input index.
Return all identifiers in preorder: emit each sorted node, then recursively emit its sorted children. Apply the same sibling rule to the roots and to every child list.
Function
sortDisplayNodes(ids: String[], parents: int[], x: int[], top: int[], bottom: int[]) → String[]Examples
Example 1
ids = ["A","B","C"]parents = [-1,-1,-1]x = [30,10,20]top = [0,5,30]bottom = [10,15,40]return = ["B","A","C"]A and B overlap, so their group uses horizontal order B, A. The disjoint group containing C comes below it.
Example 2
ids = ["rootB","rootA","childR","childL"]parents = [-1,-1,1,1]x = [20,5,30,10]top = [0,0,10,12]bottom = [5,5,20,18]return = ["rootA","childL","childR","rootB"]The roots overlap and sort by x. Preorder emits rootA, its horizontally sorted children, and then rootB.
Example 3
ids = ["A","B","C"]parents = [-1,-1,-1]x = [30,10,20]top = [0,3,7]bottom = [4,8,10]return = ["B","C","A"]A overlaps B, and B overlaps C, so all three belong to one transitive group and sort by x.
Constraints
1 <= n <= 100000, and all five arrays have lengthn.- Identifiers are unique non-empty strings of at most
50characters. - Each parent is
-1or a valid node index, and the parent links form a forest. -10^9 <= x[i], top[i], bottom[i] <= 10^9.top[i] <= bottom[i].- Intervals that share an endpoint overlap.