KatInterview

Difference-in-Differences Estimator with Baseline Gap Check

Arrays & HashingAuto-graded · 21 test cases
HardAuto-gradedArrays & Hashingcausal-inferencedata-analysisdifference-in-differences

Last 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, either 0 (baseline) or 1 (follow-up)
  • treatment[i]: group indicator, either 1 (intervention group) or 0 (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] where effect is a float and baseline_warning is 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 float
  • threshold ≥ 0
  • The baseline imbalance check uses strict inequality: when |baseline_gap| equals threshold exactly, return False

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.