FastPrepMatch a Descendant Selector in a DOM Tree

Match a Descendant Selector in a DOM Tree

Microsoft logoMicrosoft● MediumFULLTIMEONSITE INTERVIEW
Learn

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] == -1 and 0 <= parent[i] < i for every i > 0.
  • Every tag and selector token contains lowercase English letters and has length from 1 to 20.
  • The selector contains between 1 and 20 tokens separated by single spaces.

Source note: The source image is a source-neutral excerpt of the author-reported prompt.

More Microsoft problems

See Microsoft hiring insights
public int[] matchSelector(int[] parent, String[] tags, String selector) {
  // Write your code here.
}
parent[-1,0,0,1,1,2]
tags["html","body","aside","section","span","span"]
selector"body span"
expected[4]
Checking account…