BackmediumTreesAdobeInfosys

Adaptive Threshold Divergence Solution

Problem Statement

You are given a rooted tree with $N$ nodes. Each node $i$ carries an integer value $a_i$. For every node, define its adaptive threshold as the integer floor of the average of the values of all nodes in its subtree (the node itself and all its descendants). The divergence of a node is the absolute difference between its value and its adaptive threshold. Compute the sum of divergences over all nodes in the tree.

Input format:

  • The first line contains an integer $N$ – the number of nodes.
  • The second line contains $N$ integers $a_1,a_2,dots,a_N$ – the values of the nodes.
  • The next $N-1$ lines each contain two integers $u$ and $v$ describing an undirected edge between nodes $u$ and $v$. Node $1$ is the root.

Output format:

  • Output a single integer – the total divergence of all nodes.

The task requires a depth‑first traversal to compute subtree sums and sizes efficiently.

Example 1
Input
3 1 2 3 1 2 1 3
Output
1

Explanation: Subtree sums: node1 sum=6, size=3, threshold=2; node2 sum=2, size=1, threshold=2; node3 sum=3, size=1, threshold=3. Divergences: |1-2|=1, |2-2|=0, |3-3|=0. Sum=1.

Example 2
Input
5 10 20 30 40 50 1 2 1 3 3 4 3 5
Output
30

Explanation: Node1: sum=150,size=5,threshold=30,div=20. Node2: sum=20,size=1,threshold=20,div=0. Node3: sum=120,size=3,threshold=40,div=10. Node4: sum=40,size=1,threshold=40,div=0. Node5: sum=50,size=1,threshold=50,div=0. Total=30.

Example 3
Input
4 5 5 5 5 1 2 2 3 3 4
Output
0

Explanation: All nodes have value 5. Every subtree average is 5, so all divergences are 0. Sum=0.

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity expected: O(N) or O(N log N)
  • Space Complexity expected: O(1) or O(N)
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Adaptive Threshold Divergence — Problem Statement & Solution Guide

TreesMediumDepth-First Search
TimeO(N)
|
SpaceO(N)

Problem Description

You are given a rooted tree with $N$ nodes. Each node $i$ carries an integer value $a_i$. For every node, define its *adaptive threshold* as the integer floor of the average of the values of all nodes in its subtree (the node itself and all its descendants). The *divergence* of a node is the absolute difference between its value and its adaptive threshold. Compute the sum of divergences over all nodes in the tree.

Input format:

- The first line contains an integer $N$ – the number of nodes.

- The second line contains $N$ integers $a_1,a_2,dots,a_N$ – the values of the nodes.

- The next $N-1$ lines each contain two integers $u$ and $v$ describing an undirected edge between nodes $u$ and $v$. Node $1$ is the root.

Output format:

- Output a single integer – the total divergence of all nodes.

The task requires a depth‑first traversal to compute subtree sums and sizes efficiently.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Adaptive Threshold Divergence"

medium

WHY DOES IT MATTER?

This pattern exemplifies subtree aggregation, a core technique for many tree‑based queries such as subtree sums, sizes, and frequencies. Mastering it enables solving a wide class of problems that require information about a node's descendants without redundant traversals.

OPTIMIZATION CHALLENGE

The key insight is that each edge contributes to exactly one parent’s aggregate, so by processing children before their parent (post‑order), we reuse previously computed sums and sizes, collapsing an O(N^2) brute force into O(N).

REAL-WORLD CONNECTION

Think of a corporate hierarchy where each manager needs to know the total budget and headcount of their department. Computing these metrics once per employee, then propagating upward, mirrors the post‑order aggregation used here.

During an interview, write the DFS that returns a pair (subtreeSum, subtreeSize) and immediately compute the node's contribution before returning the pair upward – this keeps the code concise and avoids extra passes.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(N)

Core Theory — Why This Approach?

The problem reduces to computing, for every node, two aggregates of its subtree: the total sum of values and the count of nodes. A naive solution would recompute these aggregates independently for each node, leading to O(N^2) time on a skewed tree because each subtree traversal repeats work already done for its ancestors. The optimal paradigm is a single post‑order depth‑first search (DFS) that propagates the sum and size from children to parent, allowing each edge to be visited once. With the subtree sum S_i and size C_i known, the adaptive threshold is simply floor(S_i / C_i) = S_i // C_i, and the divergence is |a_i - (S_i // C_i)|. Summing these divergences during the same DFS yields the final answer in linear time.

Interview Questions on This Problem

Q1How would you modify the solution if the adaptive threshold were defined as the ceiling of the average instead of the floor?

Replace the integer division with (S_i + C_i - 1) // C_i to compute the ceiling, then recompute divergence as |a_i - ceil|. The rest of the DFS remains unchanged, preserving O(N) complexity.

Q2Can the algorithm be adapted to handle dynamic updates where node values change and queries for the total divergence are interleaved?

Yes. By flattening the tree with an Euler tour and building a segment tree or BIT that stores both sum and count per subtree range, each update and query can be answered in O(log N). The divergence for a node still uses sum and count from the segment tree, and the total divergence can be maintained with a Fenwick tree of per‑node divergences.

Q3Why does a recursive DFS risk stack overflow on deep trees, and how would you implement an iterative version?

Recursion depth can exceed language limits on a chain of N nodes, causing a stack overflow. An iterative DFS using an explicit stack that stores (node, parent, state) allows us to simulate post‑order processing: first push children, then after children are processed compute the node’s aggregates.

Examples

Example 1

Input

3
1 2 3
1 2
1 3

Output

1

Explanation: Subtree sums: node1 sum=6, size=3, threshold=2; node2 sum=2, size=1, threshold=2; node3 sum=3, size=1, threshold=3. Divergences: |1-2|=1, |2-2|=0, |3-3|=0. Sum=1.

Example 2

Input

5
10 20 30 40 50
1 2
1 3
3 4
3 5

Output

30

Explanation: Node1: sum=150,size=5,threshold=30,div=20. Node2: sum=20,size=1,threshold=20,div=0. Node3: sum=120,size=3,threshold=40,div=10. Node4: sum=40,size=1,threshold=40,div=0. Node5: sum=50,size=1,threshold=50,div=0. Total=30.

Example 3

Input

4
5 5 5 5
1 2
2 3
3 4

Output

0

Explanation: All nodes have value 5. Every subtree average is 5, so all divergences are 0. Sum=0.

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity expected: O(N) or O(N log N)
  • Space Complexity expected: O(1) or O(N)

Optimal Approach & Strategy

Perform one post‑order DFS that returns subtree sum and size for each node, compute its divergence on the fly, and accumulate the result. This visits each edge once, achieving O(N) time.

Brute Force Approach

For each node, traverse its entire subtree to compute sum and count, then calculate the divergence; repeat for all nodes. This repeats work and leads to O(N^2) time on deep trees.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(nums) {
   nums.sort((a, b) => a - b);
   let threshold = 0;
   for (let i = 1; i < nums.length; i++) {
       threshold += Math.abs(nums[i] - nums[i - 1]);
   }
   return nums.reduce((a, b) => a + b, 0);
}

Asked in Top Tech Interviews

AdobeInfosys

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.