LeetCode in Kotlin

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

class Solution {
    fun maxGeneticDifference(parents: IntArray, queries: Array<IntArray>): IntArray {
        val n = parents.size
        val fd = arrayOfNulls<IntArray>(n)
        for (i in 0 until n) {
            fill(parents, n, fd, i)
        }
        val ret = IntArray(queries.size)
        for (q in queries.indices) {
            var cur = queries[q][0]
            val value = queries[q][1]
            for (p in 30 downTo 0) {
                val msk = 1 shl p
                if (value and msk != cur and msk) {
                    ret[q] = ret[q] or msk
                } else if (fd[cur]!![p] >= 0) {
                    ret[q] = ret[q] or msk
                    cur = fd[cur]!![p]
                }
            }
        }
        return ret
    }

    private fun fill(parents: IntArray, n: Int, fd: Array<IntArray?>, i: Int) {
        if (fd[i] == null) {
            fd[i] = IntArray(31)
            var a = parents[i]
            if (a >= 0) {
                fill(parents, n, fd, a)
            }
            for (p in 30 downTo 0) {
                if (a == -1) {
                    fd[i]!![p] = -1
                } else {
                    if (i and (1 shl p) == a and (1 shl p)) {
                        fd[i]!![p] = fd[a]!![p]
                    } else {
                        fd[i]!![p] = a
                        a = fd[a]!![p]
                    }
                }
            }
        }
    }
}