Rollout Impact: Diff-in-Diff Estimate with Baseline Drift Check
Arrays & HashingAuto-graded · 14 test casesLast updated
Aggregate per-group, per-window means from daily records, compute a difference-in-differences estimate, and flag baseline drift between two pre-period sub-windows.
Rollout Impact Check
A product team shipped a feature on 2023-10-01. Some users received it (the treatment group) and the others did not (the control group). You are given one record per user per day and must do two things:
- Estimate the feature's effect on
daily_sessionswith a difference-in-differences (DiD) calculation. - Check whether the two groups were already drifting apart before the launch.
Input
records is a list of dictionaries, each shaped like:
{"user_id": int, "date": "YYYY-MM-DD", "group": str, "daily_sessions": float}
Windows
All bounds are inclusive. Dates are ISO strings, so they can be compared directly as strings.
| Window | Dates |
|---|---|
| Pre | 2023-09-24 to 2023-09-30 |
| Post | 2023-10-01 to 2023-10-07 |
| Early pre | 2023-09-24 to 2023-09-26 |
| Late pre | 2023-09-27 to 2023-09-30 |
Early pre and Late pre together make up Pre, so a pre-period record counts toward the Pre mean and also toward exactly one of the two sub-windows. Records outside all windows are ignored. Records whose group is not exactly "treatment" or "control" are ignored.
Means
The mean for a (group, window) pair is the plain average of daily_sessions over all records (one record is one observation) in that group and window. If a pair has no records, its mean is 0.0.
Task
Write a function that returns a dictionary with two keys.
did_estimate (float):
(mean_treatment_post - mean_treatment_pre) - (mean_control_post - mean_control_pre)
pretrend_violation (bool): let
gap_early = mean_treatment_early - mean_control_earlygap_late = mean_treatment_late - mean_control_late
Then the flag is True exactly when
abs(gap_late - gap_early) / abs(gap_early) > 0.1
The comparison is strict, so a change of exactly 10% is not a violation. If gap_early is exactly 0, the flag is False and no division is performed.
Output
{"did_estimate": <float>, "pretrend_violation": <bool>}
Constraints
- Every record has a valid
YYYY-MM-DDdate, a numericdaily_sessions, and agroupstring. - Use a single linear pass over the records; the list may be large.
- Group labels are matched exactly (case-sensitive, no trimming).
- Empty (group, window) cells give a mean of
0.0. did_estimatemust be returned as a float, andpretrend_violationas a bool.
Examples
Example 1
Input: analyze_rollout_effect([{'user_id': 1, 'date': '2023-09-24', 'group': 'treatment', 'daily_sessions': 10}, {'user_id': 2, 'date': '2023-09-24', 'group': 'control', 'daily_sessions': 5}, {'user_id': 1, 'date': '2023-09-30', 'group': 'treatment', 'daily_sessions': 10}, {'user_id': 2, 'date': '2023-09-30', 'group': 'control', 'daily_sessions': 5}, {'user_id': 1, 'date': '2023-10-01', 'group': 'treatment', 'daily_sessions': 15}, {'user_id': 2, 'date': '2023-10-01', 'group': 'control', 'daily_sessions': 5}])
Output: {'did_estimate': 5, 'pretrend_violation': False}
Hints
Hint 1
Keep a running (sum, count) for every combination of window and group, instead of storing the records themselves.
Hint 2
A single record can belong to several windows at once: a date in the Pre window also falls in either Early pre or Late pre. Check each window independently for every record.
Hint 3
Write a small mean helper that returns 0.0 for an empty cell, then build both results from those means. Check gap_early against zero before dividing, and use a strict > 0.1 for the flag.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both outputs are built from the same small set of means: one for each combination of group (treatment, control) and window (pre, post, early pre, late pre).
- Define the four windows as inclusive pairs of ISO date strings. ISO dates sort the same way lexicographically as chronologically, so
start <= date <= endworks without any parsing. - Make one pass over the records. Skip any record whose group is not exactly
treatmentorcontrol. For each remaining record, test every window and, for each window it falls in, add itsdaily_sessionsto that cell's running sum and count. A pre-period record therefore lands in the Pre cell and in either the Early or Late cell. - Define a mean helper that returns
sum / count, or0.0for an empty cell. - Compute the DiD estimate as
(T_post - T_pre) - (C_post - C_pre). - Compute the two gaps,
gap_early = T_early - C_earlyandgap_late = T_late - C_late. Ifgap_early == 0, the flag isFalse. Otherwise the flag isabs(gap_late - gap_early) / abs(gap_early) > 0.1.
Why it is correct
- The treatment group's pre-to-post change contains the true effect plus whatever would have happened anyway. The control group's change contains only the latter. Subtracting the two isolates the effect, assuming the groups would have moved in parallel without the launch.
- The pre-trend check tests that assumption on the data we can see. If the treatment-control gap shifts noticeably between the two halves of the pre-period, parallel movement is doubtful.
- Using
absin both the numerator and the denominator handles negative gaps. The strict>means a change of exactly 10% is not flagged. Guarding againstgap_early == 0avoids dividing by zero. - Each record contributes to every window it belongs to, so the Pre mean covers the full week while the Early and Late means each cover their own slice.
Complexity
- Time: O(n), with a constant amount of work (four window checks) per record.
- Space: O(1), since there are only eight (sum, count) accumulators.
Reference solution
from typing import Dict, List
def analyze_rollout_effect(records: List[Dict]) -> Dict:
windows = {
"pre": ("2023-09-24", "2023-09-30"),
"post": ("2023-10-01", "2023-10-07"),
"early": ("2023-09-24", "2023-09-26"),
"late": ("2023-09-27", "2023-09-30"),
}
# window -> group -> [sum, count]
acc = {name: {"treatment": [0.0, 0], "control": [0.0, 0]} for name in windows}
for row in records:
group = row["group"]
if group not in ("treatment", "control"):
continue
date = row["date"]
for name, (start, end) in windows.items():
if start <= date <= end:
acc[name][group][0] += row["daily_sessions"]
acc[name][group][1] += 1
def mean(window, group):
total, count = acc[window][group]
return total / count if count else 0.0
did = (mean("post", "treatment") - mean("pre", "treatment")) - (
mean("post", "control") - mean("pre", "control")
)
gap_early = mean("early", "treatment") - mean("early", "control")
gap_late = mean("late", "treatment") - mean("late", "control")
violation = False
if gap_early != 0:
violation = abs(gap_late - gap_early) / abs(gap_early) > 0.1
return {"did_estimate": float(did), "pretrend_violation": violation}