BackmediumBinary TreesGoogleAmazon

Tome Signal Detector 43 Solution

Problem Statement

You are tasked with analyzing a hierarchical sensor network represented as a binary tree. Each node in the tree contains a 'signal strength' value. The network is considered 'stable' if, for every node, the absolute difference between the sum of signal strengths in its left subtree and the sum of signal strengths in its right subtree does not exceed a given threshold K. Your goal is to determine the maximum possible value of K such that the entire tree remains stable. If no such K exists (i.e., the tree is inherently unstable even for K=0), return -1.

The input is provided as a level-order traversal of the binary tree, where null nodes are represented by -1. You must compute the subtree sums efficiently and identify the maximum imbalance observed across all nodes. The final answer is the maximum absolute difference found between left and right subtree sums for any node in the tree. If the tree is empty or contains only one node, the imbalance is 0.

Note: The subtree sum of a node includes the node's own value plus the sums of all nodes in its left and right subtrees. The imbalance at a node is defined as |sum(left_subtree) - sum(right_subtree)|, where sum(left_subtree) is the total sum of all nodes in the left subtree (excluding the current node), and similarly for the right subtree.

Example 1
Input
tree = [10, 5, 15, -1, -1, 7, 8], K = 100
Output
2

Explanation: Root (10): Left subtree sum = 5, Right subtree sum = 15 + 7 + 8 = 30. Imbalance = |5 - 30| = 25. Node 5: No children, imbalance = 0. Node 15: Left = 7, Right = 8, imbalance = |7 - 8| = 1. Node 7: No children, imbalance = 0. Node 8: No children, imbalance = 0. Maximum imbalance = 25. Wait, let me recalculate. The problem asks for the maximum K such that the tree is stable. The maximum imbalance is 25. So the answer should be 25. Let me re-read the problem. 'determine the maximum possible value of K such that the entire tree remains stable'. This means K must be at least the maximum imbalance. So the answer is the maximum imbalance. Let me correct the example. Input: [10, 5, 15, -1, -1, 7, 8]. Root: left sum=5, right sum=30, diff=25. Node 15: left=7, right=8, diff=1. Max diff=25. Output: 25.

Example 2
Input
tree = [1, 2, 3, 4, 5, 6, 7]
Output
1

Explanation: Root (1): Left subtree sum = 2 + 4 + 5 = 11, Right subtree sum = 3 + 6 + 7 = 16. Imbalance = |11 - 16| = 5. Node 2: Left = 4, Right = 5, imbalance = |4 - 5| = 1. Node 3: Left = 6, Right = 7, imbalance = |6 - 7| = 1. Nodes 4,5,6,7: No children, imbalance = 0. Maximum imbalance = 5. Output: 5.

Example 3
Input
tree = [5, -1, 10, -1, -1, 3, 7]
Output
4

Explanation: Root (5): Left subtree is empty (sum=0), Right subtree sum = 10 + 3 + 7 = 20. Imbalance = |0 - 20| = 20. Node 10: Left = 3, Right = 7, imbalance = |3 - 7| = 4. Nodes 3,7: No children, imbalance = 0. Maximum imbalance = 20. Output: 20.

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^9 <= node value <= 10^9
  • The tree is a valid binary tree (each node has at most two children)
  • The input is given as a level-order traversal array where -1 represents a null node
  • The sum of subtree values may exceed 32-bit integer range, so use 64-bit integers for calculations
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

Tome Signal Detector 43 — Problem Statement & Solution Guide

Binary TreesMediumFixed/Dynamic Window
TimeO(N)
|
SpaceO(H)

Problem Description

You are tasked with analyzing a hierarchical sensor network represented as a binary tree. Each node in the tree contains a 'signal strength' value. The network is considered 'stable' if, for every node, the absolute difference between the sum of signal strengths in its left subtree and the sum of signal strengths in its right subtree does not exceed a given threshold K. Your goal is to determine the maximum possible value of K such that the entire tree remains stable. If no such K exists (i.e., the tree is inherently unstable even for K=0), return -1.

The input is provided as a level-order traversal of the binary tree, where null nodes are represented by -1. You must compute the subtree sums efficiently and identify the maximum imbalance observed across all nodes. The final answer is the maximum absolute difference found between left and right subtree sums for any node in the tree. If the tree is empty or contains only one node, the imbalance is 0.

Note: The subtree sum of a node includes the node's own value plus the sums of all nodes in its left and right subtrees. The imbalance at a node is defined as |sum(left_subtree) - sum(right_subtree)|, where sum(left_subtree) is the total sum of all nodes in the left subtree (excluding the current node), and similarly for the right subtree.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Tome Signal Detector 43"

medium

WHY DOES IT MATTER?

It demonstrates how to aggregate information bottom‑up while enforcing a global invariant.

OPTIMIZATION CHALLENGE

Avoid recomputing subtree aggregates by caching results during a single DFS pass.

REAL-WORLD CONNECTION

Analogous to checking load balance across hierarchical servers where each subtree's traffic must stay within a tolerance.

Always return both the aggregate value and a validity flag; it lets you short‑circuit the traversal as soon as a breach is found.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The stability condition requires comparing the total signal strength of a node's left and right subtrees. By performing a post‑order traversal we can compute each subtree's sum exactly once and simultaneously verify the absolute difference constraint, turning a potentially exponential recomputation into a linear scan. Naïve approaches would recalculate subtree sums for every node, leading to O(N^2) time on skewed trees because each node would trigger a full traversal of its descendants. The optimal paradigm leverages divide‑and‑conquer: each recursive call returns both the cumulative sum and a boolean flag indicating whether the subtree rooted at that node already satisfies the stability rule, enabling early termination when a violation is found.

Interview Questions on This Problem

Q1How would you modify the algorithm to also return the first node that violates the stability condition?

Propagate the violating node up the recursion stack when a mismatch is detected, otherwise return null. The first non‑null node encountered is the earliest violation in post‑order.

Q2Can this stability check be performed iteratively without recursion?

Yes, using a stack to simulate post‑order traversal and a hashmap to store computed subtree sums. After processing children, compute the parent’s sum and validate the condition.

Q3What is the impact on complexity if the tree is stored as an adjacency list instead of node objects?

The algorithm remains O(N) because each edge is visited once; however, you need an extra visited set or parent tracking to avoid revisiting nodes. Space grows to O(N) for the adjacency structure.

Examples

Example 1

Input

tree = [10, 5, 15, -1, -1, 7, 8], K = 100

Output

2

Explanation: Root (10): Left subtree sum = 5, Right subtree sum = 15 + 7 + 8 = 30. Imbalance = |5 - 30| = 25. Node 5: No children, imbalance = 0. Node 15: Left = 7, Right = 8, imbalance = |7 - 8| = 1. Node 7: No children, imbalance = 0. Node 8: No children, imbalance = 0. Maximum imbalance = 25. Wait, let me recalculate. The problem asks for the maximum K such that the tree is stable. The maximum imbalance is 25. So the answer should be 25. Let me re-read the problem. 'determine the maximum possible value of K such that the entire tree remains stable'. This means K must be at least the maximum imbalance. So the answer is the maximum imbalance. Let me correct the example. Input: [10, 5, 15, -1, -1, 7, 8]. Root: left sum=5, right sum=30, diff=25. Node 15: left=7, right=8, diff=1. Max diff=25. Output: 25.

Example 2

Input

tree = [1, 2, 3, 4, 5, 6, 7]

Output

1

Explanation: Root (1): Left subtree sum = 2 + 4 + 5 = 11, Right subtree sum = 3 + 6 + 7 = 16. Imbalance = |11 - 16| = 5. Node 2: Left = 4, Right = 5, imbalance = |4 - 5| = 1. Node 3: Left = 6, Right = 7, imbalance = |6 - 7| = 1. Nodes 4,5,6,7: No children, imbalance = 0. Maximum imbalance = 5. Output: 5.

Example 3

Input

tree = [5, -1, 10, -1, -1, 3, 7]

Output

4

Explanation: Root (5): Left subtree is empty (sum=0), Right subtree sum = 10 + 3 + 7 = 20. Imbalance = |0 - 20| = 20. Node 10: Left = 3, Right = 7, imbalance = |3 - 7| = 4. Nodes 3,7: No children, imbalance = 0. Maximum imbalance = 20. Output: 20.

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^9 <= node value <= 10^9
  • The tree is a valid binary tree (each node has at most two children)
  • The input is given as a level-order traversal array where -1 represents a null node
  • The sum of subtree values may exceed 32-bit integer range, so use 64-bit integers for calculations

Optimal Approach & Strategy

Use a single post‑order traversal that computes subtree sums and checks the stability condition in one pass, achieving O(N) time.

Brute Force Approach

For each node, independently traverse its left and right subtrees to compute sums, leading to O(N^2) time on unbalanced trees.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(nums, K) {
   let sum = 0;
   for (let i = 0; i < nums.length; i++) {
       if (nums[i] > K) {
           sum += nums[i];
       }
   }
   return sum;
}

Asked in Top Tech Interviews

GoogleAmazonMicrosoft

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.