LeetCode #1938 — HARD

Maximum Genetic Difference Query

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

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:
- [0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2.
- [3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3.
- [2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.

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:
- [4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6.
- [1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14.
- [0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.

Constraints:

  • 2 <= parents.length <= 105
  • 0 <= parents[i] <= parents.length - 1 for every node i that is not the root.
  • parents[root] == -1
  • 1 <= queries.length <= 3 * 104
  • 0 <= nodei <= parents.length - 1
  • 0 <= vali <= 2 * 105
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: 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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Hash Map · Bit Manipulation · Trie

Example 1

[-1,0,1,1]
[[0,2],[3,2],[2,5]]

Example 2

[3,7,-1,2,0,7,0,2]
[[4,6],[1,15],[0,5]]

Related Problems

  • Maximum XOR With an Element From Array (maximum-xor-with-an-element-from-array)
Step 02

Core Insight

What unlocks the optimal approach

  • How can we use a trie to store all the XOR values in the path from a node to the root?
  • How can we dynamically add the XOR values with a DFS search?
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #1938: Maximum Genetic Difference Query
class TrieNode {
  public TrieNode[] children = new TrieNode[2];
  public int count = 0;
}

class Trie {
  public void update(int num, int val) {
    TrieNode node = root;
    for (int i = HEIGHT; i >= 0; --i) {
      final int bit = (num >> i) & 1;
      if (node.children[bit] == null)
        node.children[bit] = new TrieNode();
      node = node.children[bit];
      node.count += val;
    }
  }

  public int query(int num) {
    int ans = 0;
    TrieNode node = root;
    for (int i = HEIGHT; i >= 0; --i) {
      final int bit = (num >> i) & 1;
      final int targetBit = bit ^ 1;
      if (node.children[targetBit] != null && node.children[targetBit].count > 0) {
        ans += 1 << i;
        node = node.children[targetBit];
      } else {
        node = node.children[targetBit ^ 1];
      }
    }
    return ans;
  }

  private static final int HEIGHT = 17;
  TrieNode root = new TrieNode();
}

class Solution {
  public int[] maxGeneticDifference(int[] parents, int[][] queries) {
    final int n = parents.length;
    int[] ans = new int[queries.length];
    int rootVal = -1;
    List<Integer>[] tree = new List[n];

    for (int i = 0; i < n; ++i)
      tree[i] = new ArrayList<>();

    // {node: (index, val)}
    Map<Integer, List<Pair<Integer, Integer>>> nodeToQueries = new HashMap<>();
    Trie trie = new Trie();

    for (int i = 0; i < parents.length; ++i)
      if (parents[i] == -1)
        rootVal = i;
      else
        tree[parents[i]].add(i);

    for (int i = 0; i < queries.length; ++i) {
      final int node = queries[i][0];
      final int val = queries[i][1];
      nodeToQueries.putIfAbsent(node, new ArrayList<>());
      nodeToQueries.get(node).add(new Pair<>(i, val));
    }

    dfs(rootVal, trie, tree, nodeToQueries, ans);
    return ans;
  }

  private void dfs(int node, Trie trie, List<Integer>[] tree,
                   Map<Integer, List<Pair<Integer, Integer>>> nodeToQueries, int[] ans) {
    trie.update(node, 1);

    if (nodeToQueries.containsKey(node))
      for (Pair<Integer, Integer> query : nodeToQueries.get(node)) {
        final int i = query.getKey();
        final int val = query.getValue();
        ans[i] = trie.query(val);
      }

    for (final int child : tree[node])
      dfs(child, trie, tree, nodeToQueries, ans);

    trie.update(node, -1);
  }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n)
Space
O(1)

Approach Breakdown

SORT + SCAN
O(n log n) time
O(n) space

Sort the array in O(n log n), then scan for the missing or unique element by comparing adjacent pairs. Sorting requires O(n) auxiliary space (or O(1) with in-place sort but O(n log n) time remains). The sort step dominates.

BIT MANIPULATION
O(n) time
O(1) space

Bitwise operations (AND, OR, XOR, shifts) are O(1) per operation on fixed-width integers. A single pass through the input with bit operations gives O(n) time. The key insight: XOR of a number with itself is 0, which eliminates duplicates without extra space.

Shortcut: Bit operations are O(1). XOR cancels duplicates. Single pass → O(n) time, O(1) space.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Mutating counts without cleanup

Wrong move: Zero-count keys stay in map and break distinct/count constraints.

Usually fails on: Window/map size checks are consistently off by one.

Fix: Delete keys when count reaches zero.