Match a Descendant Selector in a DOM Tree
Problem statement
A simplified DOM contains nodes numbered from 0 to parent.length - 1. Node 0 is the root, parent[0] == -1, and parent[i] is the parent of node i. The tag name of node i is tags[i].
The space-separated selector is a descendant selector made only of tag names. A node matches when its own tag equals the last selector token and the earlier tokens can be matched, in order, by distinct ancestors; matched ancestors do not need to be adjacent.
Return the indices of all matching nodes in increasing order.
Function
matchSelector(parent: int[], tags: String[], selector: String) → int[]Examples
Example 1
parent = [-1,0,0,1,1,2]tags = ["html","body","aside","section","span","span"]selector = "body span"return = [4]Node 4 is a span below body; node 5 belongs to the aside branch.
Example 2
parent = [-1,0,1,2]tags = ["html","main","article","button"]selector = "html article button"return = [3]The main node may appear between matched descendant-selector tokens.
Constraints
1 <= parent.length == tags.length <= 100000.parent[0] == -1and0 <= parent[i] < ifor everyi > 0.- Every tag and selector token contains lowercase English letters and has length from
1to20. - The selector contains between
1and20tokens separated by single spaces.
Source note: The source image is a source-neutral excerpt of the author-reported prompt.