Array Indices Pinpointed by Subarray Sums
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Consider an undisclosed sequence of n integers indexed from 1 through n. You are given queries, a collection of 1-based inclusive index intervals (L, R) for which the contiguous slice total A[L] + A[L + 1] + ... + A[R] has been measured.
def recoverable_positions(n: int, queries: list[tuple[int, int]]) -> list[int]:
Notice that only the endpoint pairs (L, R) are provided, without the measured numeric totals. An index i (1 <= i <= n) is uniquely determined (recoverable) if and only if any two integer sequences of length n that yield identical slice totals across every interval in queries must also agree at index i.
Rules
- Intervals in
queriesmay overlap, nest inside one another, or appear more than once. - Return every uniquely determined
1-based index in strictly ascending order. - Whenever zero indices are uniquely determined, return
[-1].
Examples
Example 1
Input: n = 6, queries = [(1, 4), (2, 4), (5, 6), (5, 5)]
Output: [1, 5, 6]
- Subtracting slice
(2, 4)from slice(1, 4)isolates index1. - Slice
(5, 5)gives index5directly, and subtracting(5, 5)from(5, 6)isolates index6. - Across indices
2,3, and4, onlyA[2] + A[3] + A[4]is constrained, so adding+1toA[2]and-1toA[3]leaves every measured slice unchanged.
Example 2
Input: n = 5, queries = [(1, 2), (2, 3), (3, 4), (4, 5)]
Output: [-1]
- Adding an alternating offset
[+t, -t, +t, -t, +t]for any non-zero integertkeeps every consecutive pair sumA[k] + A[k + 1]unchanged while altering all five entries, so no index is pinned down.
Example 3
Input: n = 3, queries = [(1, 3), (1, 2), (2, 3)]
Output: [1, 2, 3]
- Even without any single-element interval,
A[3] = sum(1, 3) - sum(1, 2),A[1] = sum(1, 3) - sum(2, 3), andA[2] = sum(1, 2) - A[1], determining every position.
Constraints
1 <= n <= 10^51 <= len(queries) <= 10^51 <= L <= R <= nfor every(L, R)inqueries
Step-by-step walkthrough
Understand what "recoverable" really means
We have an unknown
1-indexed integer sequenceA[1..n](n <= 100,000) and a listqueriesof up to100,000inclusive intervals(L, R)whose contiguous sumsA[L] + ... + A[R]were recorded. Notice we do not even receive the numeric totals — only which index spans were measured!Index
iis recoverable whenever any two integer sequences that match on all listed slice sums are forced to share the exact same value atA[i]. We return all recoverable1-based indices in ascending order, or[-1]when none can be pinned down.Two quick cases show why naive intuition can trip you up:
- Being covered is not enough: if
n = 2andqueries = [(1, 2)], we only knowA[1] + A[2]. Both[0, 0]and[1, -1]produce slice sum0, so neither index is recoverable ([-1]). - Overlapping slices can combine: in Example 3 (
n = 3,queries = [(1, 3), (1, 2), (2, 3)]), no single-element slice appears, yetsum(1, 3) - sum(1, 2)isolatesA[3],sum(1, 3) - sum(2, 3)isolatesA[1], andsum(1, 2) - A[1]isolatesA[2]([1, 2, 3]).
- Being covered is not enough: if
Why solving linear equations directly is too slow
You can view each query
(L, R)as a linear equation with1s in columnsL..Rand0s elsewhere. In principle, solving that system ofqequations innvariables by Gaussian elimination tells you which variables are uniquely determined.However, row-reducing a matrix of size
100,000 x 100,000takes roughlyO(q * n * min(q, n))work — on the order of10^15operations! That only works on tiny test cases. To handle10^5elements in milliseconds, we need to exploit the fact that every equation sums a contiguous slice ofA.Key insight: turn range sums into fencepost differences
Whenever a problem revolves around contiguous range sums, introduce prefix sums: define
n + 1"fenceposts"P[0], P[1], ..., P[n]whereP[0] = 0andP[k] = A[1] + A[2] + ... + A[k]:Fenceposts: P[0] ------ P[1] ------ P[2] ------ P[3] ------ P[4] ------ P[5] Spans : A[1] A[2] A[3] A[4] A[5] Known range (L, R) : A[L] + ... + A[R] = P[R] - P[L - 1] Target element A[i]: A[i] = P[i] - P[i - 1]Look at what just happened! Every equation now mentions only two variables instead of up to
nvariables:- Knowing the sum of range
(L, R)means we know the exact differenceP[R] - P[L - 1]between fencepostL - 1and fencepostR. - Recovering element
A[i]means knowing the exact differenceP[i] - P[i - 1]between adjacent fencepostsi - 1andi.
So build an undirected graph on the
n + 1fenceposts0, 1, ..., nwhere each query(L, R)adds an edge betweenL - 1andR!- Knowing the sum of range
Why connectivity is both sufficient and necessary
Does "fenceposts
i - 1andiare in the same connected component" completely characterize whenA[i]is recoverable? Let's check both directions:- If
i - 1andiare connected,A[i]IS recoverable: walk any pathv_0 -> v_1 -> ... -> v_mfromv_0 = i - 1tov_m = i. Every edge along the path has a known differenceP[v_t] - P[v_{t-1}]. Adding those differences along the path cancels every middle term (telescoping sum), leavingP[i] - P[i - 1] = A[i]! - If
i - 1andiare NOT connected,A[i]is NOT recoverable: sincei - 1andilie in two separate connected components, fencepost0can belong to at most one of them. Pick whichever componentCdoes not contain0, and add+1toP[v]for every fencepostvinsideC:- Because
0is outsideC,P[0]stays0, and allP[v]remain integers, so the shifted prefix sums define a valid integer arrayA'. - Every query edge
(L - 1, R)has either both endpoints insideC((+1) - (+1) = 0change) or both endpoints outsideC(0 - 0 = 0change), so every listed range sum is unchanged! - Between
i - 1andi, one endpoint is insideCand the other is outsideC, soA'[i] = P'[i] - P'[i - 1]changes by+1or-1!
- Because
Here is that exact
+1shift in action on Example 2 (n = 5,queries = [(1, 2), (2, 3), (3, 4), (4, 5)]):Query ranges -> Fencepost edges (L - 1, R): (1, 2) -> 0--2 (2, 3) -> 1--3 (3, 4) -> 2--4 (4, 5) -> 3--5 Components: Even fenceposts: {0, 2, 4} (contains 0 -> keep P unchanged: 0, 0, 0) Odd fenceposts : {1, 3, 5} (does not contain 0 -> shift P by +1!) Fencepost P : P[0]=0 P[1]=1 P[2]=0 P[3]=1 P[4]=0 P[5]=1 Array A' : A[1]=+1 A[2]=-1 A[3]=+1 A[4]=-1 A[5]=+1 Every listed pair sum is still 0, yet every A[i] changed -> Output: [-1]- If
Track connected components fast with Union-Find
All we need is to add
qedges on nodes0..nand then test whether(i - 1)andisit in the same component for eachi = 1..n. Union-Find (Disjoint Set Union) is tailor-made for this:parent[x]points toward the root representative ofx's component (parent[x] == xat a root).- Path halving inside an iterative
whileloop points each visited node to its grandparent, flattening trees without risking Python's recursion limit on100,000nodes. - Union by size attaches the smaller tree under the larger root so tree depth stays tiny.
def find_root(parent: List[int], node: int) -> int: """Return the root representative of `node` using iterative path halving.""" # Point each visited node to its grandparent so future lookups stay nearly flat. while parent[node] != node: parent[node] = parent[parent[node]] node = parent[node] return node def union_nodes(parent: List[int], comp_size: List[int], node_a: int, node_b: int) -> None: """Merge the connected components containing `node_a` and `node_b` by size.""" root_a = find_root(parent, node_a) root_b = find_root(parent, node_b) if root_a == root_b: return # Attach the smaller tree under the larger root to keep tree height O(log n). if comp_size[root_a] < comp_size[root_b]: root_a, root_b = root_b, root_a parent[root_b] = root_a comp_size[root_a] += comp_size[root_b]Link the query endpoints and trace Example 1
Allocate
parentandcomp_sizeof lengthn + 1(for fenceposts0throughn), unionleft - 1withrightfor every query, and then scanifrom1ton(which collects recoverable indices in ascending order automatically).def recoverable_positions(n: int, queries: list[tuple[int, int]]) -> list[int]: # Prefix nodes 0..n represent P[0] = 0 and P[k] = A[1] + ... + A[k]. # parent[x] stores the parent of prefix node x (x is a root when parent[x] == x). parent = list(range(n + 1)) # comp_size[r] stores how many prefix nodes belong to root r's component. comp_size = [1] * (n + 1) # Phase 1: Range sum A[left..right] equals P[right] - P[left - 1], # so knowing (left, right) links prefix node (left - 1) with prefix node right. for left, right in queries: union_nodes(parent, comp_size, left - 1, right) # Phase 2: Single element A[i] equals P[i] - P[i - 1], which is uniquely determined # if and only if adjacent prefix nodes (i - 1) and i lie in the same component. recoverable: List[int] = [] for i in range(1, n + 1): if find_root(parent, i - 1) == find_root(parent, i): recoverable.append(i) # Phase 3: Problem rule requires returning [-1] when zero positions are recoverable. if not recoverable: return [-1] return recoverableLet's trace Example 1 (
n = 6,queries = [(1, 4), (2, 4), (5, 6), (5, 5)]):Queries -> Edges (L - 1, R): (1, 4) -> union(0, 4) (2, 4) -> union(1, 4) (5, 6) -> union(4, 6) (5, 5) -> union(4, 5) Connected components on fenceposts 0..6: Component A: {0, 1, 4, 5, 6} Isolated nodes: {2}, {3} Check each A[i] = P[i] - P[i - 1]: i = 1: nodes (0, 1) -> both in Comp A -> YES i = 2: nodes (1, 2) -> diff components -> NO i = 3: nodes (2, 3) -> diff components -> NO i = 4: nodes (3, 4) -> diff components -> NO i = 5: nodes (4, 5) -> both in Comp A -> YES i = 6: nodes (5, 6) -> both in Comp A -> YES Output: [1, 5, 6]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def find_root(parent: List[int], node: int) -> int: """Return the root representative of `node` using iterative path halving.""" # Point each visited node to its grandparent so future lookups stay nearly flat. while parent[node] != node: parent[node] = parent[parent[node]] node = parent[node] return node def union_nodes(parent: List[int], comp_size: List[int], node_a: int, node_b: int) -> None: """Merge the connected components containing `node_a` and `node_b` by size.""" root_a = find_root(parent, node_a) root_b = find_root(parent, node_b) if root_a == root_b: return # Attach the smaller tree under the larger root to keep tree height O(log n). if comp_size[root_a] < comp_size[root_b]: root_a, root_b = root_b, root_a parent[root_b] = root_a comp_size[root_a] += comp_size[root_b] def recoverable_positions(n: int, queries: list[tuple[int, int]]) -> list[int]: # Prefix nodes 0..n represent P[0] = 0 and P[k] = A[1] + ... + A[k]. # parent[x] stores the parent of prefix node x (x is a root when parent[x] == x). parent = list(range(n + 1)) # comp_size[r] stores how many prefix nodes belong to root r's component. comp_size = [1] * (n + 1) # Phase 1: Range sum A[left..right] equals P[right] - P[left - 1], # so knowing (left, right) links prefix node (left - 1) with prefix node right. for left, right in queries: union_nodes(parent, comp_size, left - 1, right) # Phase 2: Single element A[i] equals P[i] - P[i - 1], which is uniquely determined # if and only if adjacent prefix nodes (i - 1) and i lie in the same component. recoverable: List[int] = [] for i in range(1, n + 1): if find_root(parent, i - 1) == find_root(parent, i): recoverable.append(i) # Phase 3: Problem rule requires returning [-1] when zero positions are recoverable. if not recoverable: return [-1] return recoverable✅ Submit now — all tests should pass.
Intuition & how it works
Picture n road segments of unknown integer lengths A[1], ..., A[n] placed end-to-end between n + 1 mileposts numbered 0, 1, ..., n, with milepost 0 anchored at 0. Each milepost k sits at the prefix sum P[k] = A[1] + ... + A[k] — the cumulative sum of the first k elements (with P[0] = 0). When a query specifies a contiguous interval (L, R), knowing A[L] + ... + A[R] is equivalent to knowing P[R] - P[L - 1]: the exact signed offset between milepost L - 1 and milepost R! Meanwhile, asking whether a single element A[i] is uniquely determined is asking whether we can deduce P[i] - P[i - 1], the offset between adjacent mileposts i - 1 and i. Adding an undirected edge between L - 1 and R for each query means A[i] is pinned down if and only if mileposts i - 1 and i belong to the same connected component (a group of nodes mutually reachable via paths of edges): any path between i - 1 and i lets us add and subtract slice sums until all intermediate mileposts telescope away, whereas if i - 1 and i lie in separate components, shifting every milepost in the non-0 component by +1 changes A[i] without altering a single measured slice sum! We maintain those components in near-constant time per edge using Union-Find — a forest data structure that merges node sets and checks whether two nodes share a common root.
Why do simpler ideas fall short? Checking whether index i is merely covered by at least one interval fails on Example 2 (n = 5, queries = [(1, 2), (2, 3), (3, 4), (4, 5)]), where every position is covered yet [+1, -1, +1, -1, +1] leaves all four consecutive pair sums untouched. Checking only single-element intervals or nested pairs misses multi-slice combinations like Example 3 (n = 3, queries = [(1, 3), (1, 2), (2, 3)]), which recovers [1, 2, 3] with zero length-1 queries. Solving the full linear system via Gaussian elimination (row-reducing an equation matrix to isolate variables) requires roughly O(q * n * min(q, n)) work — around 10^15 operations when n = q = 100,000.
Let's trace Example 1 (n = 6, queries = [(1, 4), (2, 4), (5, 6), (5, 5)]) on mileposts 0..6:
Step 1: Convert each 1-indexed interval (L, R) into milepost edge (L - 1, R):
(1, 4) -> union(0, 4)
(2, 4) -> union(1, 4) => component {0, 1, 4}
(5, 6) -> union(4, 6) => component {0, 1, 4, 6}
(5, 5) -> union(4, 5) => component {0, 1, 4, 5, 6}; mileposts {2} and {3} stand alone
Step 2: Check adjacent mileposts (i - 1, i) for A[i] = P[i] - P[i - 1]:
i = 1: (0, 1) -> same component! -> A[1] = sum(1,4) - sum(2,4)
i = 2: (1, 2) -> different components -> A[2] NOT determined
i = 3: (2, 3) -> different components -> A[3] NOT determined
i = 4: (3, 4) -> different components -> A[4] NOT determined
i = 5: (4, 5) -> same component! -> A[5] = sum(5,5)
i = 6: (5, 6) -> same component! -> A[6] = sum(5,6) - A[5]
Result: [1, 5, 6]
Complexity
Let n be the sequence length and q = len(queries) be the number of measured intervals.
- Time:
O((n + q) * alpha(n)), wherealpha(n)is the inverse Ackermann function (an extraordinarily slow-growing function that stays<= 4for all realistic memory sizes). Allocatingparentandcomp_sizetakesO(n)time; iterating throughqueriesperformsqunion_nodescalls, and scanningi = 1..nperforms2nfind_rootcalls. Combining union by size (always attaching the smaller tree beneath the larger root) with path halving (pointing each visited node to its grandparent duringfind_root) keeps every Union-Find operation atO(alpha(n))amortized time. - Space:
O(n). Bothparentandcomp_sizestoren + 1integers for prefix nodes0..n, and therecoverableresult list holds at mostnindices (O(1)auxiliary space per query).
Edge cases
- Single-element sequence (
n = 1):(1, 1)links nodes0and1and returns[1]. - Zero determined positions: For
n = 3, queries = [(1, 3)], only nodes0and3are linked, so no adjacent pair(i - 1, i)shares a root and the function returns[-1](never[]). - Repeated intervals: Calling
union_nodeson an already-merged pair seesroot_a == root_band returns immediately without corruptingcomp_size. - Nested intervals sharing an endpoint:
(1, 6)links0--6and(2, 6)links1--6, connecting0and1via6and pinning downA[1]. - Alternating parity chains: Measuring every consecutive pair
(i, i + 1)as in Example 2 links even mileposts{0, 2, 4, ...}into one component and odd mileposts{1, 3, 5, ...}into a second component, determining nothing ([-1]); adding a single length-1query such as(1, 1)(0--1) merges both components and immediately pins down allnelements! - List vs. tuple intervals: Unpacking
for left, right in queries:works identically whether intervals arrive as(L, R)tuples or[L, R]lists.
Common mistakes
- Linking
leftandrightinstead ofleft - 1andright: This off-by-one error is the #1 pitfall! UnioningLandRturns a length-1query(1, 1)into a useless self-loop1--1and returns[-1]instead of[1]. Always use then + 1prefix fenceposts0..n. - Returning
[]instead of[-1]: Whenever no index is uniquely determined, the return contract requires[-1]. - Using unguarded recursion in
find_root: Naive recursive Union-Find can form chains of depth100,000and raiseRecursionErrorin Python. Iterativefind_rootpaired with union by size avoids recursion completely. - Requiring connectivity to node
0: Node0anchorsP[0] = 0, which determines absolute prefix sumsP[k], yetA[5] = P[5] - P[4]is determined by(5, 5)alone (4--5) even if neither4nor5connects to0! Always testfind_root(parent, i - 1) == find_root(parent, i), neverfind_root(parent, i) == find_root(parent, 0).
Alternative approaches
- Breadth-First Search (BFS) or iterative Depth-First Search (DFS): Construct an explicit undirected graph on vertices
0..nwithqedges(L - 1, R), label connected components inO(n + q)time, and output everyiwherecomp[i - 1] == comp[i]. This runs in strict linearO(n + q)time at the cost ofO(n + q)memory for adjacency lists rather thanO(n).
Follow-up questions
- How would you compute the actual values of all pinned-down elements if each query also supplied its numeric range sum? Extend Union-Find into a weighted Union-Find that maintains
potential[x] = P[x] - P[root]for every nodexrelative to its component's root. Each measured slice(L, R, S)assertsP[R] - P[L - 1] = S; ifL - 1andRlie in different components, link their roots and choose the root offset to satisfy that difference, whereas if they already share a root, verifypotential[R] - potential[L - 1] == Sto catch inconsistent inputs. Afterward, every determined indexihas valueA[i] = potential[i] - potential[i - 1]. - What is the fewest extra range queries needed so that every index in the array becomes uniquely determined? Pinning down every
A[1..n]requires every consecutive pair(0, 1), (1, 2), ..., (n - 1, n)to be connected — meaning alln + 1prefix nodes must belong to one connected component. If the graph currently hasCconnected components, each additional query adds one edge and lowers the component count by at most1, soC - 1extra queries is both necessary and sufficient: pick one representative node from each component, sort themv_1 < v_2 < ... < v_C, and query intervals(v_1 + 1, v_2), (v_2 + 1, v_3), ..., (v_{C-1} + 1, v_C). - How could you report the count of uniquely determined indices online after each new range arrives? Store the member list of every component alongside a running counter
determined_count. Wheneverunion_nodesmerges two distinct components, iterate over each nodexin the smaller component and check whetherx - 1(forx >= 1) orx + 1(forx < n) sits in the larger component, incrementingdetermined_countfor each newly connected adjacent pair before concatenating the member lists. Because a node is scanned only when its component's size at least doubles, each of then + 1nodes is inspected at mostlog2(n + 1)times overall, yieldingO(n log n + q * alpha(n))total work andO(1)time per count query.
Follow-up questions
- How would you compute the actual values of all pinned-down elements if each query also supplied its numeric range sum?
- What is the fewest extra range queries needed so that every index in the array becomes uniquely determined?
- How could you report the count of uniquely determined indices online after each new range arrives?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array