Filter Data with Composable Predicates
Problem statement
Filter an integer list using a predicate built from strict greater-than and less-than comparisons and logical AND and OR.
For this exercise, assume predicate is a valid binary expression tree encoded as an array of three-integer nodes. Node i uses one of these forms:
[0, threshold, 0]: acceptxwhenx > threshold.[1, threshold, 0]: acceptxwhenx < threshold.[2, left, right]: the logical AND of child nodesleftandright.[3, left, right]: the logical OR of child nodesleftandright.
Every child index is smaller than its parent index. The final node is the root, every other node has exactly one parent, and every node belongs to the tree. The third entry of a comparison leaf is always 0 and has no meaning.
Return the values from data for which the root predicate is true. Preserve their input order and repeated occurrences. If none match, return an empty array. Do not modify either input.
Function
filterData(data: int[], predicate: int[][]) → int[]Examples
Example 1
data = [1,4,6,9,4]predicate = [[0,3,0],[1,8,0],[2,0,1]]return = [4,6,4]The predicate is x > 3 AND x < 8. Both occurrences of 4 and the value 6 match, in their original order.
Example 2
data = [-5,-1,0,2,5]predicate = [[1,-2,0],[0,2,0],[3,0,1]]return = [-5,5]The predicate accepts values below -2 or above 2. The value equal to 2 does not pass a strict comparison.
Example 3
data = []predicate = [[0,0,0]]return = []An empty input has no values to retain.
Constraints
- For this exercise, assume
0 <= data.length <= 1000. 1 <= predicate.length <= 101, and every row has exactly three integers.- Every input value and comparison threshold is an integer from
-10^9through10^9. - The node array is a valid binary tree with the stated node forms, child ordering, root and parent rules.