Forward Cumulative Loss Across Policy Renewal Terms

Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen

Problem Statement

An insurance carrier tracks incurred claim costs across successive renewal periods in a table named policy_term_losses. Each record represents one renewal period (term_id) belonging to a parent contract (policy_id), sequenced chronologically by the integer term_sequence (where larger integers denote later renewal periods).

For every record in policy_term_losses, compute its forward cumulative loss (ultimate_loss): the total of loss_amount on that record plus loss_amount across every subsequent renewal period under the same policy_id (i.e., all rows sharing policy_id whose term_sequence is greater than or equal to the current row's term_sequence).

Emit one output row per input row (in any row order) with five columns:

  • policy_id
  • term_id
  • term_sequence
  • loss_amount
  • ultimate_loss (rounded to 2 decimal places)

Input Schema

Table policy_term_losses:

Column Type Description
policy_id VARCHAR Contract identifier
term_id VARCHAR Renewal period identifier (maps to a single policy_id)
term_sequence INTEGER Chronological index within policy_id (higher values are later)
term_start_date DATE Effective start date of the period
term_end_date DATE Expiration date of the period
loss_amount DECIMAL(18,2) Net incurred loss recorded for this period

Examples

Example 1

Input (policy_term_losses):

policy_id term_id term_sequence term_start_date term_end_date loss_amount
POL-10 TRM-1 1 2021-06-01 2022-05-31 240.00
POL-10 TRM-2 2 2022-06-01 2023-05-31 85.50
POL-10 TRM-3 3 2023-06-01 2024-05-31 34.50
POL-20 TRM-9 1 2023-01-15 2024-01-14 120.00

Expected output:

policy_id term_id term_sequence loss_amount ultimate_loss
POL-10 TRM-1 1 240.00 360.00
POL-10 TRM-2 2 85.50 120.00
POL-10 TRM-3 3 34.50 34.50
POL-20 TRM-9 1 120.00 120.00

Walk-through: Within POL-10, sequence 1 sums sequences 1, 2, 3 (240.00 + 85.50 + 34.50 = 360.00), sequence 2 sums sequences 2, 3 (85.50 + 34.50 = 120.00), and sequence 3 keeps its own 34.50. POL-20 is partitioned independently and has a single period (120.00).

Example 2

Input (policy_term_losses):

policy_id term_id term_sequence term_start_date term_end_date loss_amount
POL-55 RN-1 1 2020-04-01 2021-03-31 500.00
POL-55 RN-2 2 2021-04-01 2022-03-31 -120.00
POL-55 RN-3 3 2022-04-01 2023-03-31 0.00
POL-55 RN-4 4 2023-04-01 2024-03-31 45.00

Expected output:

policy_id term_id term_sequence loss_amount ultimate_loss
POL-55 RN-1 1 500.00 425.00
POL-55 RN-2 2 -120.00 -75.00
POL-55 RN-3 3 0.00 45.00
POL-55 RN-4 4 45.00 45.00

Walk-through: Downward reserve revisions (-120.00) and zero-loss periods (0.00) combine algebraically with later periods: sequence 2 evaluates to -120.00 + 0.00 + 45.00 = -75.00, and sequence 1 evaluates to 500.00 + (-75.00) = 425.00.

Constraints

  • Every (policy_id, term_sequence) combination appears at most once, and each term_id belongs to a single policy_id.
  • Sequence order depends solely on term_sequence (never on term_id text order or term_start_date / term_end_date, which may even be NULL).
  • loss_amount may be positive, zero, or negative (or NULL, which contributes nothing to a sum).
  • Return rows in any order.

Step-by-step walkthrough

  1. Understand what ultimate loss means per term

    We are given policy_term_losses(policy_id, term_id, term_sequence, term_start_date, term_end_date, loss_amount), with one row per policy term. Within each policy_id, the integer term_sequence gives chronological order (larger numbers mean later renewal terms), and (policy_id, term_sequence) has at most one row.

    We must return every input row (no collapsing) with a fifth column ultimate_loss: the sum of loss_amount from the current term through the final term of that same policy:

    Policy POL-10 ordered by term_sequence:
      TRM-1 (seq 1): loss = 240.00  --->  [240.00 + 85.50 + 34.50] = 360.00
      TRM-2 (seq 2): loss =  85.50  --->          [85.50 + 34.50]  = 120.00
      TRM-3 (seq 3): loss =  34.50  --->                  [34.50]  =  34.50
    

    Notice that term_start_date and term_end_date are not needed at all — even if a date is NULL, term_sequence alone defines which terms come at or after the current term.

  2. Start with the brute-force mental model

    We can translate the definition word for word into SQL using a correlated subquery — an inner SELECT that looks up matching future rows f for each outer row t:

    SELECT
        t.policy_id,
        t.term_id,
        t.term_sequence,
        t.loss_amount,
        ROUND(
            (SELECT SUM(f.loss_amount)
             FROM policy_term_losses AS f
             WHERE f.policy_id = t.policy_id
               AND f.term_sequence >= t.term_sequence),
            2
        ) AS ultimate_loss
    FROM policy_term_losses AS t
    

    This produces the right answer, but for a policy with k terms it re-scans up to k rows for each of those k terms (O(k^2) work per policy). Because we are simply computing a reverse running total (a suffix sum) within each policy, a window function can compute every term's answer in one pass over sorted rows.

  3. Build the forward-looking window frame

    A window function computes an aggregate across related rows without merging them into a single row. Inside SUM(loss_amount) OVER (...), three clauses control which rows get summed:

    1. PARTITION BY policy_id: splits the table into separate per-policy buckets so losses from POL-10 never leak into POL-20.
    2. ORDER BY term_sequence: lines up a policy's terms from earliest to latest (1, 2, 3, ...).
    3. RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING: sets the window frame — the slice of the partition summed for the current row — to start at the current term_sequence value and extend all the way to the last row of that policy.

    Why must we write out the frame explicitly? Whenever ORDER BY appears inside OVER (...) with no frame clause, SQL defaults to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW — summing from the first term up to the current term (240.0, 325.5, 360.0, or "loss to date"), which is the exact opposite direction!

    Default frame (UNBOUNDED PRECEDING .. CURRENT ROW):    [TRM-1] -> [TRM-1..TRM-2] -> [TRM-1..TRM-3]  (240.0, 325.5, 360.0)
    Forward frame (CURRENT ROW .. UNBOUNDED FOLLOWING):    [TRM-1..TRM-3] -> [TRM-2..TRM-3] -> [TRM-3]  (360.0, 120.0,  34.5)
    

    Because (policy_id, term_sequence) is unique, ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING (or flipping the sort to ORDER BY term_sequence DESC with ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) gives the exact same values. Using RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING reads closest to the mathematical rule term_sequence >= current term_sequence, and would even include tied sequence numbers together if duplicates ever occurred.

  4. Round away SQLite floating-point noise

    In PostgreSQL or Snowflake, DECIMAL(18, 2) arithmetic is exact in base 10. SQLite, however, stores decimal fractions as binary floating-point numbers, where 10.10 + 20.20 + 0.30 evaluates to 30.599999999999998. Wrapping the window sum in ROUND(..., 2) keeps every ultimate_loss clean to 2 decimal places while leaving loss_amount untouched:

        ROUND(
            SUM(loss_amount) OVER (
                -- Keep each policy isolated so losses never cross policy boundaries.
                PARTITION BY policy_id
                -- Order terms chronologically and sum from current row to final term.
                ORDER BY term_sequence
                RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
            ),
            -- Round to 2 decimals so SQLite binary floats stay exact to the cent.
            2
        ) AS ultimate_loss
    
  5. Trace Example 1 and Example 2 (including negative adjustments)

    Let's trace both Example 1 (POL-10 and POL-20) and Example 2 (POL-55, which has a downward -120.00 reserve revision and a 0.00 term):

    policy_id  term_id  seq  loss_amount  terms summed in frame            ultimate_loss
    ---------  -------  ---  -----------  -------------------------------  -------------
    POL-10     TRM-1    1     240.00      240.00 + 85.50 + 34.50            360.00
    POL-10     TRM-2    2      85.50      85.50 + 34.50                     120.00
    POL-10     TRM-3    3      34.50      34.50                              34.50
    POL-20     TRM-9    1     120.00      120.00                            120.00
    
    POL-55     RN-1     1     500.00      500.00 + (-120.00) + 0.00 + 45.00  425.00
    POL-55     RN-2     2    -120.00      (-120.00) + 0.00 + 45.00           -75.00
    POL-55     RN-3     3       0.00      0.00 + 45.00                        45.00
    POL-55     RN-4     4      45.00      45.00                               45.00
    

    Negative and zero losses need no special CASE handling — ordinary addition handles downward adjustments naturally, even when ultimate_loss drops below zero.

  6. Complete SQL query

    SELECT
        policy_id,
        term_id,
        term_sequence,
        loss_amount,
        -- Sum this term and every later term (term_sequence >= current) within the
        -- same policy while keeping one output row per policy term.
        ROUND(
            SUM(loss_amount) OVER (
                -- Keep each policy isolated so losses never cross policy boundaries.
                PARTITION BY policy_id
                -- Order terms chronologically and sum from current row to final term.
                ORDER BY term_sequence
                RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
            ),
            -- Round to 2 decimals so SQLite binary floats stay exact to the cent.
            2
        ) AS ultimate_loss
    FROM policy_term_losses
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine opening a folder for a single insurance policy that holds one page per renewal term (Term 1, Term 2, Term 3). A normal running total adds from the first page downward to answer "what is our loss to date?" Here we want the mirror image — starting on any term's page, what is the sum of this term's loss plus every future term's loss through the end of the policy, written right onto each page without removing any pages from the folder.

Naive approaches either lose rows or repeat work unnecessarily. Using GROUP BY policy_id collapses an entire policy down to a single summary row instead of keeping one row per term, while a correlated subquery (an inner SELECT that re-executes for every outer row) re-scans a policy's k terms for each of its k rows in O(k^2) time. Even with a window function (a SQL OVER (...) calculation that attaches a group or sequence summary to each row without collapsing rows), writing SUM(loss_amount) OVER (PARTITION BY policy_id ORDER BY term_sequence) without specifying a window frame (the exact range of rows inside the partition included in each row's calculation) defaults to summing from the first term up to the current row — computing loss-to-date instead of remaining ultimate loss.

Tracing POL-10 from Example 1 ((TRM-1, seq 1, 240.00), (TRM-2, seq 2, 85.50), (TRM-3, seq 3, 34.50)), PARTITION BY policy_id isolates POL-10 from POL-20, and ORDER BY term_sequence lines its losses up as [240.00, 85.50, 34.50]. The explicit frame RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING tells the engine to sum from the current row to the end of POL-10's partition: 240.00 + 85.50 + 34.50 = 360.0 at TRM-1, 85.50 + 34.50 = 120.0 at TRM-2, and 34.5 at TRM-3.

Complexity

  • Time — O(N log N) without an index, or O(N) with a composite index: Let N be the total number of rows across all policies. Without an index, the database sorts all N rows by (policy_id, term_sequence) in O(N log N) time and then sweeps through each partition (each isolated per-policy group of rows) in O(N) time to maintain the sliding window sum (compared to O(k^2) per k-term policy for a self-join or correlated subquery). With a composite B-tree index on policy_term_losses(policy_id, term_sequence), the engine reads rows already sorted in window order, skipping the O(N log N) sort completely; adding term_id, loss_amount creates a covering index (an index holding every column the query touches) so the main table never needs to be read.
  • Space — O(N): Sorting and buffering partitions for window evaluation takes O(N) memory across the N output rows (or O(k) per policy of k terms when reading in index order).

Edge cases

  • Single-term policies: The forward frame contains only that single row, so ultimate_loss equals loss_amount.
  • Negative adjustments and zero-loss terms: Downward reserve adjustments (loss_amount < 0) and 0 losses add normally, meaning an earlier term's ultimate_loss can be smaller than its own loss_amount or even negative (-120.00 + 0.00 + 45.00 = -75.00 in Example 2).
  • Gaps in term_sequence or string-sorting traps in term_id: Sequence gaps like 2, 9, 10 or string IDs where 'T10' < 'T2' alphabetically do not affect the result because ordering uses the integer term_sequence.
  • Missing (NULL) dates: term_start_date and term_end_date are never referenced, so NULL dates on newly created renewal terms do not change the order.
  • Binary floating-point cents in SQLite: SQLite stores DECIMAL values using binary floating-point numbers (base-2 approximations where 10.10 + 20.20 + 0.30 yields 30.599999999999998), which ROUND(..., 2) cleans up.
  • NULL loss_amount: SQL's SUM ignores NULL values and sums the remaining non-NULL terms in the frame (returning NULL only if every term from the current row onward has NULL loss_amount).
  • Empty table: Returns zero rows with the five required column names.

Common mistakes

  • Omitting RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING: With ORDER BY term_sequence alone, SQL defaults to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, returning forward cumulative loss-to-date (240.0, 325.5, 360.0) instead of ultimate loss (360.0, 120.0, 34.5).
  • Forgetting PARTITION BY policy_id: Without partitioning, one policy's losses continue summing into every policy that sorts after it.
  • Ordering by term_id or term_start_date: Alphabetical ordering puts 'T10' before 'T2', and NULL dates sort first in SQLite, scrambling the chronological term order.
  • Using GROUP BY policy_id: Grouping collapses each policy to one row instead of preserving one row per policy term.
  • Filtering term_sequence in the same WHERE clause: WHERE runs before window functions, so WHERE term_sequence = 1 strips out later terms before SUM(...) OVER (...) can include them; always filter specific terms in an outer query around a CTE.

Follow-up questions

  • How would you return cumulative loss-to-date and each term's fraction of total policy loss alongside ultimate loss? Combine three window frames over PARTITION BY policy_id in one SELECT: the default ORDER BY term_sequence frame for loss_to_date, our CURRENT ROW AND UNBOUNDED FOLLOWING frame for ultimate_loss, and an unordered OVER (PARTITION BY policy_id) window for total policy loss (guarding division with NULLIF(..., 0) since negative adjustments can make a policy's net total 0):

sql SELECT policy_id, term_id, term_sequence, ROUND(SUM(loss_amount) OVER (PARTITION BY policy_id ORDER BY term_sequence), 2) AS loss_to_date, ROUND( 1.0 * loss_amount / NULLIF(SUM(loss_amount) OVER (PARTITION BY policy_id), 0), 4 ) AS share_of_policy_loss FROM policy_term_losses

  • How could you express the same forward sum in SQL dialects that lack window functions? Self-join each policy term t to every term f of the same policy with f.term_sequence >= t.term_sequence, then GROUP BY t's columns and sum f.loss_amount. This produces identical results (because (policy_id, term_sequence) is unique) at the cost of O(k^2) work per k-term policy:

sql SELECT t.policy_id, t.term_id, t.term_sequence, t.loss_amount, ROUND(SUM(f.loss_amount), 2) AS ultimate_loss FROM policy_term_losses AS t JOIN policy_term_losses AS f ON f.policy_id = t.policy_id AND f.term_sequence >= t.term_sequence GROUP BY t.policy_id, t.term_id, t.term_sequence, t.loss_amount

  • How would you compute this column on a pandas DataFrame in Python? Sort each policy in descending term_sequence order (last term -> first term), then run a grouped cumulative sum (groupby("policy_id")["loss_amount"].cumsum()) and round to 2 decimal places — reversing the sort order turns a forward suffix sum into pandas' standard top-down cumsum():

python df = df.sort_values(["policy_id", "term_sequence"], ascending=[True, False]) df["ultimate_loss"] = df.groupby("policy_id")["loss_amount"].cumsum().round(2)

Follow-up questions

Similar questions

More Plymouth Rock Assurance Corporation interview questions

All 1 Plymouth Rock Assurance Corporation questions →