LeetCode-in-Java

1938. Maximum Genetic Difference Query

Hard

There is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node’s number denotes its unique genetic value (i.e. the genetic value of node x is x). The genetic difference between two genetic values is defined as the bitwise-XOR of their values. You are given the integer array parents, where parents[i] is the parent for node i. If node x is the root of the tree, then parents[x] == -1.

You are also given the array queries where queries[i] = [nodei, vali]. For each query i, find the maximum genetic difference between vali and pi, where pi is the genetic value of any node that is on the path between nodei and the root (including nodei and the root). More formally, you want to maximize vali XOR pi.

Return an array ans where ans[i] is the answer to the ith query.

Example 1:

Input: parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]]

Output: [2,3,7]

Explanation: The queries are processed as follows:

Example 2:

Input: parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]]

Output: [6,14,7]

Explanation: The queries are processed as follows:

Constraints:

Solution

public class Solution {
    public int[] maxGeneticDifference(int[] parents, int[][] queries) {
        int n = parents.length;
        int[][] fd = new int[n][];
        for (int i = 0; i < n; i++) {
            fill(parents, n, fd, i);
        }
        int[] ret = new int[queries.length];
        for (int q = 0; q < queries.length; q++) {
            int cur = queries[q][0];
            int value = queries[q][1];
            for (int p = 30; p >= 0; p--) {
                int msk = 1 << p;
                if ((value & msk) != (cur & msk)) {
                    ret[q] |= msk;
                } else if (fd[cur][p] >= 0) {
                    ret[q] |= msk;
                    cur = fd[cur][p];
                }
            }
        }
        return ret;
    }

    private void fill(int[] parents, int n, int[][] fd, int i) {
        if (fd[i] == null) {
            fd[i] = new int[31];
            int a = parents[i];
            if (a >= 0) {
                fill(parents, n, fd, a);
            }
            for (int p = 30; p >= 0; p--) {
                if (a == -1) {
                    fd[i][p] = -1;
                } else {
                    if ((i & (1 << p)) == (a & (1 << p))) {
                        fd[i][p] = fd[a][p];
                    } else {
                        fd[i][p] = a;
                        a = fd[a][p];
                    }
                }
            }
        }
    }
}