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 queries may 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 index 1.
  • Slice (5, 5) gives index 5 directly, and subtracting (5, 5) from (5, 6) isolates index 6.
  • Across indices 2, 3, and 4, only A[2] + A[3] + A[4] is constrained, so adding +1 to A[2] and -1 to A[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 integer t keeps every consecutive pair sum A[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), and A[2] = sum(1, 2) - A[1], determining every position.

Constraints

  • 1 <= n <= 10^5
  • 1 <= len(queries) <= 10^5
  • 1 <= L <= R <= n for every (L, R) in queries

Step-by-step walkthrough

  1. Understand what "recoverable" really means

    We have an unknown 1-indexed integer sequence A[1..n] (n <= 100,000) and a list queries of up to 100,000 inclusive intervals (L, R) whose contiguous sums A[L] + ... + A[R] were recorded. Notice we do not even receive the numeric totals — only which index spans were measured!

    Index i is recoverable whenever any two integer sequences that match on all listed slice sums are forced to share the exact same value at A[i]. We return all recoverable 1-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 = 2 and queries = [(1, 2)], we only know A[1] + A[2]. Both [0, 0] and [1, -1] produce slice sum 0, 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, yet sum(1, 3) - sum(1, 2) isolates A[3], sum(1, 3) - sum(2, 3) isolates A[1], and sum(1, 2) - A[1] isolates A[2] ([1, 2, 3]).
  2. Why solving linear equations directly is too slow

    You can view each query (L, R) as a linear equation with 1s in columns L..R and 0s elsewhere. In principle, solving that system of q equations in n variables by Gaussian elimination tells you which variables are uniquely determined.

    However, row-reducing a matrix of size 100,000 x 100,000 takes roughly O(q * n * min(q, n)) work — on the order of 10^15 operations! That only works on tiny test cases. To handle 10^5 elements in milliseconds, we need to exploit the fact that every equation sums a contiguous slice of A.

  3. 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] where P[0] = 0 and P[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 n variables:

    • Knowing the sum of range (L, R) means we know the exact difference P[R] - P[L - 1] between fencepost L - 1 and fencepost R.
    • Recovering element A[i] means knowing the exact difference P[i] - P[i - 1] between adjacent fenceposts i - 1 and i.

    So build an undirected graph on the n + 1 fenceposts 0, 1, ..., n where each query (L, R) adds an edge between L - 1 and R!

  4. Why connectivity is both sufficient and necessary

    Does "fenceposts i - 1 and i are in the same connected component" completely characterize when A[i] is recoverable? Let's check both directions:

    • If i - 1 and i are connected, A[i] IS recoverable: walk any path v_0 -> v_1 -> ... -> v_m from v_0 = i - 1 to v_m = i. Every edge along the path has a known difference P[v_t] - P[v_{t-1}]. Adding those differences along the path cancels every middle term (telescoping sum), leaving P[i] - P[i - 1] = A[i]!
    • If i - 1 and i are NOT connected, A[i] is NOT recoverable: since i - 1 and i lie in two separate connected components, fencepost 0 can belong to at most one of them. Pick whichever component C does not contain 0, and add +1 to P[v] for every fencepost v inside C:
      1. Because 0 is outside C, P[0] stays 0, and all P[v] remain integers, so the shifted prefix sums define a valid integer array A'.
      2. Every query edge (L - 1, R) has either both endpoints inside C ((+1) - (+1) = 0 change) or both endpoints outside C (0 - 0 = 0 change), so every listed range sum is unchanged!
      3. Between i - 1 and i, one endpoint is inside C and the other is outside C, so A'[i] = P'[i] - P'[i - 1] changes by +1 or -1!

    Here is that exact +1 shift 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]
    
  5. Track connected components fast with Union-Find

    All we need is to add q edges on nodes 0..n and then test whether (i - 1) and i sit in the same component for each i = 1..n. Union-Find (Disjoint Set Union) is tailor-made for this:

    • parent[x] points toward the root representative of x's component (parent[x] == x at a root).
    • Path halving inside an iterative while loop points each visited node to its grandparent, flattening trees without risking Python's recursion limit on 100,000 nodes.
    • 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]
    
  6. Link the query endpoints and trace Example 1

    Allocate parent and comp_size of length n + 1 (for fenceposts 0 through n), union left - 1 with right for every query, and then scan i from 1 to n (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 recoverable
    

    Let'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]
    
  7. 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)), where alpha(n) is the inverse Ackermann function (an extraordinarily slow-growing function that stays <= 4 for all realistic memory sizes). Allocating parent and comp_size takes O(n) time; iterating through queries performs q union_nodes calls, and scanning i = 1..n performs 2n find_root calls. Combining union by size (always attaching the smaller tree beneath the larger root) with path halving (pointing each visited node to its grandparent during find_root) keeps every Union-Find operation at O(alpha(n)) amortized time.
  • Space: O(n). Both parent and comp_size store n + 1 integers for prefix nodes 0..n, and the recoverable result list holds at most n indices (O(1) auxiliary space per query).

Edge cases

  • Single-element sequence (n = 1): (1, 1) links nodes 0 and 1 and returns [1].
  • Zero determined positions: For n = 3, queries = [(1, 3)], only nodes 0 and 3 are linked, so no adjacent pair (i - 1, i) shares a root and the function returns [-1] (never []).
  • Repeated intervals: Calling union_nodes on an already-merged pair sees root_a == root_b and returns immediately without corrupting comp_size.
  • Nested intervals sharing an endpoint: (1, 6) links 0--6 and (2, 6) links 1--6, connecting 0 and 1 via 6 and pinning down A[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-1 query such as (1, 1) (0--1) merges both components and immediately pins down all n elements!
  • 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 left and right instead of left - 1 and right: This off-by-one error is the #1 pitfall! Unioning L and R turns a length-1 query (1, 1) into a useless self-loop 1--1 and returns [-1] instead of [1]. Always use the n + 1 prefix fenceposts 0..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 depth 100,000 and raise RecursionError in Python. Iterative find_root paired with union by size avoids recursion completely.
  • Requiring connectivity to node 0: Node 0 anchors P[0] = 0, which determines absolute prefix sums P[k], yet A[5] = P[5] - P[4] is determined by (5, 5) alone (4--5) even if neither 4 nor 5 connects to 0! Always test find_root(parent, i - 1) == find_root(parent, i), never find_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..n with q edges (L - 1, R), label connected components in O(n + q) time, and output every i where comp[i - 1] == comp[i]. This runs in strict linear O(n + q) time at the cost of O(n + q) memory for adjacency lists rather than O(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 node x relative to its component's root. Each measured slice (L, R, S) asserts P[R] - P[L - 1] = S; if L - 1 and R lie in different components, link their roots and choose the root offset to satisfy that difference, whereas if they already share a root, verify potential[R] - potential[L - 1] == S to catch inconsistent inputs. Afterward, every determined index i has value A[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 all n + 1 prefix nodes must belong to one connected component. If the graph currently has C connected components, each additional query adds one edge and lowers the component count by at most 1, so C - 1 extra queries is both necessary and sufficient: pick one representative node from each component, sort them v_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. Whenever union_nodes merges two distinct components, iterate over each node x in the smaller component and check whether x - 1 (for x >= 1) or x + 1 (for x < n) sits in the larger component, incrementing determined_count for 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 the n + 1 nodes is inspected at most log2(n + 1) times overall, yielding O(n log n + q * alpha(n)) total work and O(1) time per count query.

Follow-up questions

Similar questions

More Ethos interview questions

All 1 Ethos questions →