Interview Questions/Coding/Range Power Query Ledger

Range Power Query Ledger

Preview mode. Log in to edit, run, submit, and save progress.

Hard

Range Power Query Ledger

An analytics engine receives an array and many offline range requests. For a requested segment, define its power as the sum over every distinct value x in that segment of count(x)^2 multiplied by x. Return the power for each request in the original order. Input Format: The first line contains t. Each case starts with n and q, then n values. Each of the next q lines contains l and r for a 1-indexed inclusive range. Output Format: For every request, print the segment power.

Examples

Example 1
Input:
1
5 3
1 2 1 3 2
1 3
2 5
1 5
Output:
6

Explanation: For each query, count each value inside the requested segment and apply count squared times the value.

Approach hint

When one value enters the range, only that value's contribution changes.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

solution.cpp