Difference-in-Differences Estimator with Baseline Gap Check
Arrays & HashingAuto-graded · 21 test casesLast updated
Tests understanding of causal inference mechanics by computing a DID treatment effect and flagging baseline imbalance from panel observations.
You receive three equal-length arrays representing observations from a controlled experiment with pre- and post-intervention measurements:
period[i]: time indicator, either0(baseline) or1(follow-up)treatment[i]: group indicator, either1(intervention group) or0(comparison group)outcome[i]: measured result (float)
Your function must return a list [effect, baseline_warning] where:
A) Treatment Effect (Difference-in-Differences)
Calculate the DID estimator:
effect = (mean_followup_intervention - mean_baseline_intervention) - (mean_followup_comparison - mean_baseline_comparison)
This measures how much the intervention group's change differs from the comparison group's change.
B) Baseline Imbalance Warning
Compute the baseline gap: baseline_gap = mean_baseline_intervention - mean_baseline_comparison
Return baseline_warning = True if |baseline_gap| > threshold, otherwise False.
Return Format
- If any of the four cells (baseline×intervention, baseline×comparison, follow-up×intervention, follow-up×comparison) contains zero observations, return
[None, None] - Otherwise return
[effect, baseline_warning]whereeffectis a float andbaseline_warningis a boolean
Constraints
- 1 ≤ length of arrays ≤ 100,000
- All three arrays have identical length
period[i]∈ {0, 1}treatment[i]∈ {0, 1}outcome[i]is a valid floatthreshold≥ 0- The baseline imbalance check uses strict inequality: when
|baseline_gap|equalsthresholdexactly, returnFalse
Examples
Example 1
Input: calculate_did_effect([0, 0, 1, 1], [0, 1, 0, 1], [10, 12, 11, 16], 1)
Output: [3, True]
Example 2
Input: calculate_did_effect([0, 0, 1, 1], [0, 1, 0, 1], [5, 5.5, 7, 8], 0.5)
Output: [0.5, False]
Example 3
Input: calculate_did_effect([0, 1, 1], [0, 0, 1], [2, 3, 5], 0)
Output: [None, None]
Hints
Hint 1
The data naturally partitions into four groups defined by the Cartesian product of period and treatment values. Compute the mean outcome for each group.
Hint 2
A single pass through the arrays can accumulate both sums and counts for all four groups simultaneously, achieving O(n) time and O(1) space.
Hint 3
The DID formula cancels out both time-invariant differences between groups and time effects common to both groups, isolating the causal effect under parallel trends assumptions.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The observations partition into four distinct cells based on the combination of time period and group membership:
| Comparison (0) | Intervention (1) | |
|---|---|---|
| Baseline (0) | mean₀₀ | mean₀₁ |
| Follow-up (1) | mean₁₀ | mean₁₁ |
Both requested outputs depend exclusively on these four cell means:
- DID effect = (mean₁₁ − mean₀₁) − (mean₁₀ − mean₀₀)
- Baseline gap = mean₀₁ − mean₀₀, with warning triggered when |gap| > threshold
The most efficient implementation makes one pass through the data, accumulating observations into the four cells, then computes cell means and applies the formulas.
Why This Works
The difference-in-differences estimator removes two potential sources of bias:
- Time-invariant group differences: By taking the difference within each group (follow-up minus baseline), any constant offset between groups cancels out
- Common time shocks: By subtracting the comparison group's change from the intervention group's change, any time trend affecting both groups equally is eliminated
What remains is the causal effect of the intervention under the parallel trends assumption (both groups would have followed the same trajectory absent treatment).
The baseline imbalance check serves as a warning signal. While DID tolerates level differences between groups, a large baseline gap suggests the groups may not be comparable, raising doubts about whether parallel trends holds.
Complexity
- Time: O(n) for a single pass through all three arrays
- Space: O(1) auxiliary space, storing only four lists (or equivalently, eight accumulators for sums and counts)
Implementation
from typing import List
def calculate_did_effect(period: List[int], treatment: List[int], outcome: List[float], threshold: float) -> List[object]:
cells = {(p, t): [] for p in (0, 1) for t in (0, 1)}
for p, t, value in zip(period, treatment, outcome):
cells[(p, t)].append(value)
# Without all four cell means, neither requested result is defined.
if any(not values for values in cells.values()):
return [None, None]
means = {key: sum(values) / len(values) for key, values in cells.items()}
did = (means[(1, 1)] - means[(0, 1)]) - (means[(1, 0)] - means[(0, 0)])
pretrend = abs(means[(0, 1)] - means[(0, 0)]) > threshold
return [did, pretrend]