FastPrepMode of a Ternary Search Tree

Mode of a Ternary Search Tree

Google logoGoogle● EasyNEW GRADPHONE SCREEN
Learn

Problem statement

A ternary search tree is encoded by a node table nodes. Row i is [value, leftIndex, middleIndex, rightIndex], row 0 is the root, and -1 means that a child is absent.

  • Every node in a left subtree has a smaller value than its parent.
  • Every node in a middle subtree has the same value as its parent.
  • Every node in a right subtree has a larger value than its parent.

Return the mode: the value that occurs most often. If several values have the same highest frequency, return the smallest one.

Function

ternaryTreeMode(nodes: int[][]) → int

Examples

Example 1

nodes = [[5,1,2,3],[3,-1,-1,-1],[5,-1,4,-1],[8,-1,-1,-1],[5,-1,-1,-1]]return = 5

The value 5 occurs three times.

Example 2

nodes = [[2,1,2,3],[1,-1,-1,-1],[2,-1,-1,-1],[3,-1,-1,-1]]return = 2

The root value occurs twice.

Example 3

nodes = [[7,-1,-1,-1]]return = 7

A one-node tree has that node's value as its mode.

Constraints

  • 1 <= nodes.length <= 200000.
  • Each row has exactly four integers.
  • Every nonnegative child index is valid, every node is reachable exactly once from row 0, and the stated ternary-search-tree invariant holds.

More Google problems

See Google hiring insights
public int ternaryTreeMode(int[][] nodes) {
    // Write your code here.
}
nodes[[5,1,2,3],[3,-1,-1,-1],[5,-1,4,-1],[8,-1,-1,-1],[5,-1,-1,-1]]
expected5
Checking account…