BackmediumTreesUberPaytm

Balanced Tree Span Calculator 2 Solution

Problem Statement

Balanced Tree Span Calculator 2

You are given a perfectly balanced binary tree with N nodes, where N is a power of two. The nodes are numbered in level‑order starting from 1, and each node holds an integer value. For a node v, its balanced tree span is defined as the sum of the values of all nodes in the subtree rooted at v (including v itself). Your task is to answer Q queries; each query supplies a node index v and you must output the balanced tree span of that node.

Input format:

  • The first line contains an integer N (1 ≤ N ≤ 10^5), the number of nodes.
  • The second line contains N integers, the values of the nodes in level‑order.
  • The third line contains an integer Q (1 ≤ Q ≤ 10^5), the number of queries.
  • Each of the next Q lines contains a single integer v (1 ≤ v ≤ N), the index of the queried node.

Output format: For each query, output a single line containing the balanced tree span of the specified node.

The tree is guaranteed to be a complete binary tree, so the subtree of any node corresponds to a contiguous segment in the level‑order array. This property allows the use of a segment tree to answer all queries in O((N+Q) log N) time.

Example 1
Input
7 1 2 3 4 5 6 7 3 1 2 4
Output
28 11 4

Explanation: The tree has 7 nodes. The subtree of node 1 includes all nodes, so its sum is 1+2+3+4+5+6+7=28. Node 2’s subtree contains nodes 2,4,5 with values 2+4+5=11. Node 4 is a leaf, so its subtree sum is just 4.

Example 2
Input
4 10 -5 3 2 2 2 3
Output
-3 3

Explanation: Node 2’s subtree includes nodes 2 and 4: -5+2=-3. Node 3 is a leaf with value 3.

Example 3
Input
8 5 1 2 3 4 6 7 8 4 1 5 6 8
Output
36 12 6 8

Explanation: Node 1’s subtree contains all nodes: 5+1+2+3+4+6+7+8=36. Node 5’s subtree includes nodes 5 and 8: 4+8=12. Node 6 is a leaf with value 6. Node 8 is a leaf with value 8.

Constraints

  • 1 ≤ N ≤ 10^5
  • N is a power of two
  • -10^9 ≤ value of each node ≤ 10^9
  • 1 ≤ Q ≤ 10^5
  • 1 ≤ v ≤ 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

Balanced Tree Span Calculator 2 — Problem Statement & Solution Guide

TreesMediumSegment Tree Range Query
TimeO(N + Q)
|
SpaceO(N)

Problem Description

Balanced Tree Span Calculator 2

You are given a perfectly balanced binary tree with N nodes, where N is a power of two. The nodes are numbered in level‑order starting from 1, and each node holds an integer value. For a node v, its *balanced tree span* is defined as the sum of the values of all nodes in the subtree rooted at v (including v itself). Your task is to answer Q queries; each query supplies a node index v and you must output the balanced tree span of that node.

Input format:

- The first line contains an integer N (1 ≤ N ≤ 10^5), the number of nodes.

- The second line contains N integers, the values of the nodes in level‑order.

- The third line contains an integer Q (1 ≤ Q ≤ 10^5), the number of queries.

- Each of the next Q lines contains a single integer v (1 ≤ v ≤ N), the index of the queried node.

Output format:

For each query, output a single line containing the balanced tree span of the specified node.

The tree is guaranteed to be a complete binary tree, so the subtree of any node corresponds to a contiguous segment in the level‑order array. This property allows the use of a segment tree to answer all queries in O((N+Q) log N) time.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Balanced Tree Span Calculator 2"

medium

WHY DOES IT MATTER?

Precomputing subtree sums transforms an expensive per‑query traversal into a constant‑time lookup, which is essential when the number of queries is large. It also eliminates repeated work, a common source of timeouts in interview settings.

OPTIMIZATION CHALLENGE

The key insight is that the tree is static; therefore, a single DFS can compute all subtree sums in linear time, after which queries become trivial. This reduces the per‑query cost from O(N) to O(1).

REAL-WORLD CONNECTION

Consider a distributed log aggregation system where each server aggregates logs from its child nodes. Instead of recomputing the aggregate for every request, the system pre‑computes and caches the sum of logs for each subtree, enabling instant query responses.

When explaining this in an interview, emphasize the separation of concerns: first a one‑time pre‑processing phase (DFS) and then a constant‑time query phase. Highlight that the DFS depth is bounded by log N for a perfect binary tree, so recursion is safe.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

In a perfectly balanced binary tree where nodes are numbered in level‑order, each node’s *balanced tree span* is simply the sum of all values in its subtree. A naive solution would recompute this sum for every query by walking the subtree, leading to a worst‑case time of O(N·Q) and quickly becoming infeasible for large N and Q. The optimal paradigm is to perform a single depth‑first traversal of the tree once, computing and storing the subtree sum for every node. After this pre‑processing, each query can be answered in O(1) by looking up the stored value. This approach reduces the overall complexity to O(N+Q) time and O(N) space, which is the best possible for static trees with point queries.

Interview Questions on This Problem

Q1How would you efficiently answer multiple subtree sum queries on a static perfect binary tree?

I would perform a single DFS to compute the sum of each subtree and store it in an array indexed by node number. Each query then becomes an O(1) lookup, giving an overall O(N+Q) solution.

Q2What is the time complexity of the naive approach for this problem and why is it impractical for large inputs?

The naive approach visits every node in the queried subtree, giving O(size_of_subtree) per query. In the worst case, size_of_subtree can be O(N), so for Q queries the complexity is O(N·Q), which is too slow when N and Q are up to 10^5 or more.

Q3Explain how the tree’s level‑order numbering influences your choice of data structure for answering queries.

Level‑order numbering means children of node i are 2i and 2i+1, but subtrees are not contiguous in this order. Therefore, a simple prefix sum array over the level‑order list would not work. Instead, we use a DFS to map each node to its subtree sum, storing it in an array indexed by node number, which aligns with the numbering scheme.

Examples

Example 1

Input

7
1 2 3 4 5 6 7
3
1
2
4

Output

28
11
4

Explanation: The tree has 7 nodes. The subtree of node 1 includes all nodes, so its sum is 1+2+3+4+5+6+7=28. Node 2’s subtree contains nodes 2,4,5 with values 2+4+5=11. Node 4 is a leaf, so its subtree sum is just 4.

Example 2

Input

4
10 -5 3 2
2
2
3

Output

-3
3

Explanation: Node 2’s subtree includes nodes 2 and 4: -5+2=-3. Node 3 is a leaf with value 3.

Example 3

Input

8
5 1 2 3 4 6 7 8
4
1
5
6
8

Output

36
12
6
8

Explanation: Node 1’s subtree contains all nodes: 5+1+2+3+4+6+7+8=36. Node 5’s subtree includes nodes 5 and 8: 4+8=12. Node 6 is a leaf with value 6. Node 8 is a leaf with value 8.

Constraints

  • 1 ≤ N ≤ 10^5
  • N is a power of two
  • -10^9 ≤ value of each node ≤ 10^9
  • 1 ≤ Q ≤ 10^5
  • 1 ≤ v ≤ N

Optimal Approach & Strategy

First run a DFS to compute and store the subtree sum for every node. Then answer each query by returning the stored sum in O(1) time.

Brute Force Approach

For each query, traverse the subtree rooted at the given node and sum all node values, resulting in O(size_of_subtree) time per query.

Verified Code Solutions

JavaScript Solution
Time: O(N + Q)
function solution(root) {
   if (!root) return 0;
   function dfs(node) {
       if (!node) return 0;
       return node.val + dfs(node.left) + dfs(node.right);
   }
   return dfs(root.left) + dfs(root.right);
}

Asked in Top Tech Interviews

UberPaytm

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.