Data Scientist interview preparation

Data Scientist Interview Questions

20 frequently asked Data Scientist interview questions. Data science is an in-demand field that turns product, customer, and business data into decisions, experiments, models, and measurable insights. The questions cover different levels, and you can practice answering them aloud in our interview trainer.

Start a Data Scientist AI InterviewNo credit card required. 1 free session available.
Technical interview practice in EnglishA mode where non-native speakers can practice passing technical interviews.

Beginner questions

1How do covariance and correlation differ when comparing two numeric variables?

Covariance is E[(X − E[X])(Y − E[Y])], or its sample analogue, and indicates whether deviations from the two means tend to have the same or opposite sign. Its magnitude depends on both variables' units: changing meters to centimeters changes covariance. Pearson correlation divides covariance by the product of the standard deviations, giving a unitless value between −1 and 1 when both variances are positive. It is unchanged by positive linear rescaling, while reversing one variable's sign reverses correlation. Neither measure establishes causation, and zero covariance or Pearson correlation does not imply independence; a nonlinear relationship can have zero linear association. Outliers and mixed subgroups can strongly affect both. I would inspect a scatterplot and consider a rank-based measure when monotonic rather than linear association is the relevant question.

Try answering this question with an AI coach

2What is the conceptual difference between inner, left, right, and full outer joins, and how does each choice change the analytical population and null handling in downstream metric computation?

Inner, left, right, and full outer joins define which records are retained when combining tables based on matching keys: - Inner Join: Retains only records where the join key matches in both tables. - Left (Outer) Join: Retains all records from the left table and populates columns from the right table with NULL when there is no match. - Right (Outer) Join: Retains all records from the right table, populating unmatched left-side columns with NULL. - Full Outer Join: Retains all records from both tables, populating NULLs on either side when a match is absent. Analytical Population & Downstream Metric Impact: The choice of join directly controls the analytical cohort and the denominators used in metric calculation. An unintentional inner join between a user base and an activity/transaction table drops inactive users, shrinking the denominator to active users only and artificially inflating conversion or retention rates. Conversely, outer joins preserve the full baseline population but introduce NULLs for non-matching rows. Downstream calculations must account for these NULLs: standard SQL aggregates like SUM() or AVG() ignore NULL values, COUNT(column) counts non-NULL entries while COUNT(*) counts all rows, and arithmetic operations on uncoalesced NULLs evaluate to NULL.

-- Inner join silently shrinks denominator to purchasers only
SELECT COUNT(o.order_id) * 1.0 / COUNT(u.user_id) AS inner_conv_rate
FROM users u
INNER JOIN orders o ON u.user_id = o.user_id;

-- Left join preserves full user base for accurate metric computation
SELECT COUNT(o.order_id) * 1.0 / COUNT(u.user_id) AS true_conv_rate
FROM users u
LEFT JOIN orders o ON u.user_id = o.user_id;
Try answering this question with an AI coach

3In product experimentation, what does randomization achieve that simple before-after comparison usually cannot, and how would you explain the core causal claim an A/B test is designed to support?

In product experimentation, a simple before-after comparison compares metrics across different time periods, which confounds the effect of a feature change with external temporal factors such as seasonality, day-of-week patterns, concurrent marketing campaigns, macro trends, and natural user maturation. Randomization assigns eligible units simultaneously to treatment and control groups, balancing both observed and unobserved confounding variables across groups in expectation. This establishes internal validity. The core causal claim supported by an A/B test relies on counterfactual reasoning: because the control group is subjected to the exact same external conditions over the exact same time window, it serves as an empirical estimate of the counterfactual—what would have happened to the treatment group had they not received the feature. Therefore, any statistically significant difference in outcomes can be causally attributed to the treatment intervention.

# Naive Before-After Comparison:
# Effect_estimate = Metric_t1 (Holiday Launch) - Metric_t0 (Pre-Holiday Baseline)
# Problem: Lift is confounded by holiday shopping surge and marketing spend.

# Randomized A/B Test:
# Effect_estimate = E[Metric_Holiday | Treatment] - E[Metric_Holiday | Control]
# Solution: Both arms experience the exact same external shocks simultaneously.
Try answering this question with an AI coach

4What does exploratory data analysis typically aim to accomplish before formal modeling or experimentation, and how do you distinguish EDA from confirmatory analysis?

Exploratory Data Analysis (EDA) is an open-ended process aimed at understanding the underlying structure of a dataset, uncovering patterns, identifying anomalies or data quality issues, assessing distributional assumptions, and generating hypotheses before building formal statistical models or running experiments. The core distinction between EDA and confirmatory analysis lies in their intent and methodology: EDA is hypothesis-generating, flexible, and exploratory—using descriptive summaries, correlations, and visualizations to explore what the data suggests without strict pre-commitments. In contrast, confirmatory analysis (such as hypothesis testing or A/B test evaluation) is hypothesis-testing, structured, and inferential—designed to rigorously test pre-specified, falsifiable hypotheses while controlling for statistical error rates (e.g., Type I error). Treating findings uncovered during EDA as confirmed conclusions on the same dataset can lead to data dredging (p-hacking) and overfitting.

import numpy as np
import pandas as pd

# 1. EDA Phase: Open-ended discovery and hypothesis generation
df = pd.DataFrame({'engagement_score': np.random.normal(50, 10, 1000)})
summary = df['engagement_score'].describe()

# 2. Confirmatory Phase: Testing pre-registered hypothesis on fresh test/experiment data
# (e.g., two-sample t-test with fixed significance level alpha = 0.05)
Try answering this question with an AI coach

5What is target leakage in a supervised learning setting, and how does it differ from legitimate strong correlation between a feature and the label?

Target leakage occurs when a feature included in model training contains information about the target label that would not legitimately be available at inference time when the model makes real-world predictions. This frequently happens when a feature is collected chronologically after the event of interest or is a direct artifact/downstream consequence of the target outcome (such as using an account cancellation timestamp or a refund ID to predict customer churn). In contrast, legitimate strong correlation reflects a genuine, pre-existing predictive or causal relationship that is fully known and available before the prediction point (such as a customer's login frequency over the past 30 days). While both will show high feature importance or strong evaluation metrics, a model with target leakage will achieve unrealistically high offline validation scores but fail in production because the leaky feature cannot be known at inference time.

# Scenario: Predicting whether a user will cancel their subscription (is_churned)

# LEAKY FEATURE:
# 'cancellation_survey_submitted' -> Occurs after the decision to churn has executed.

# LEGITIMATE FEATURE:
# 'login_count_last_30_days' -> Observed strictly before the prediction cut-off date.
Try answering this question with an AI coach

6What is the purpose of partitioning data into training, validation, and test sets, and how should each partition guide iterative model development?

Partitioning data into training, validation, and test sets isolates model fitting, hyperparameter tuning, and final evaluation to ensure generalization to unseen data. - Training Set: Used to fit the internal parameters of the model (e.g., weights and biases in neural networks, split thresholds in trees). - Validation Set: Used during iterative development for model selection, hyperparameter tuning, feature selection, and detecting overfitting. It guides decisions on which model architecture or configuration performs best without touching the final evaluation data. - Test Set: Serves as a strictly held-out proxy for unseen production data. It is evaluated only once at the very end of the project to provide an unbiased estimate of generalization error. Re-tuning models based on test set results invalidates its objectivity and introduces optimistic bias.

from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification

X, y = make_classification(n_samples=1000, n_features=10, random_state=42)

# Step 1: Split off final test set (20%)
X_dev, X_test, y_dev, y_test = train_test_split(
    X, y, test_size=0.20, random_state=42, stratify=y
)

# Step 2: Split remaining development data into train (75% of dev = 60% total) and validation (25% of dev = 20% total)
X_train, X_val, y_train, y_val = train_test_split(
    X_dev, y_dev, test_size=0.25, random_state=42, stratify=y_dev
)

print(f"Train size: {len(X_train)}, Val size: {len(X_val)}, Test size: {len(X_test)}")
Try answering this question with an AI coach

7What is the distinction between supervised and unsupervised learning, and how do label availability and business objectives determine which paradigm to choose?

Supervised learning algorithms learn a mathematical mapping from input features (X) to known target labels (y) using labeled historical data to predict outcomes on unseen observations. Unsupervised learning analyzes datasets containing only features (X) to discover intrinsic structures, natural groupings (clustering), or reduced representations without predefined target labels. The choice between paradigms is driven by label availability and business objectives: if ground-truth labels exist or are feasible to collect, and the business goal is targeted prediction (e.g., fraud detection, churn prediction, price forecasting), supervised learning is appropriate. If ground-truth labels do not exist, are prohibitively expensive to acquire, or the objective is open-ended exploration (e.g., customer segmentation, anomaly detection without known labels), unsupervised learning is chosen.

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.cluster import KMeans

X = np.array([[10, 2], [12, 3], [1, 8], [2, 9]])
y = np.array([0, 0, 1, 1])

# Supervised: Learns mapping X -> y
clf = LogisticRegression().fit(X, y)

# Unsupervised: Discovers clusters directly from X
kmeans = KMeans(n_clusters=2, random_state=42, n_init=10).fit(X)
Try answering this question with an AI coach

8What is a North Star Metric, and how do you distinguish an effective North Star from a vanity metric when evaluating product health?

A North Star Metric (NSM) is the primary metric that best captures the core value a product delivers to its customers while driving sustainable business outcomes (e.g., 'Nights Booked' for Airbnb or 'Weekly Active Streaming Hours' for a music platform). It aligns product teams around long-term customer value rather than superficial growth. To distinguish an effective North Star from a vanity metric: 1. Value Alignment: An effective North Star reflects actual user utility and active engagement, whereas a vanity metric measures superficial volume (such as total registered users, cumulative app downloads, or raw page views) that can grow even when users immediately churn. 2. Actionability and Correlation: An effective North Star correlates with user retention, product health, and monetization, and responds directly to improvements in product quality. Vanity metrics often cannot be tied to genuine retention or business health and are prone to superficial inflation.

Platform: Vacation Rental App
Vanity Metric: Cumulative app downloads (increases continuously even if 95% of users uninstall immediately).
North Star Metric: Nights booked per active user (reflects actual value exchange between guests and hosts).
Try answering this question with an AI coach

9What is the practical distinction between data drift and concept drift, and why is categorizing them correctly essential for post-launch model maintenance?

Input data drift means the feature distribution P(X) changes. Pure covariate shift additionally assumes P(Y|X) is unchanged; observing input drift alone cannot establish that assumption. In contrast, concept drift occurs when the underlying relationship between inputs and the target P(Y|X) changes, meaning identical feature values now correspond to different target behaviors or outcomes. Categorizing them correctly is vital for post-launch maintenance because input drift and concept drift may coexist and call for different responses. Under pure covariate shift, historical conditional relationships remain valid where there is support; maintenance focuses on expanding training coverage across new feature regions, updating preprocessing, or applying sample re-weighting. With concept drift, some historical relationships may become less relevant. Evaluate recent labeled data and affected slices, then decide whether to reweight old examples, retrain, redesign, or change the decision policy; drift does not automatically imply a material performance loss.

# Data Drift (Covariate Shift):
# User demographics or devices change (P(X) shifts),
# but genuine vs fraudulent transaction patterns remain identical (P(Y|X) unchanged).

# Concept Drift:
# Fraudsters adapt tactics to mimic normal shopping patterns;
# identical feature inputs now have a higher probability of fraud (P(Y|X) shifts).
Try answering this question with an AI coach

10What is the distinction between a population parameter and a sample statistic, and how does sampling variability impact metric interpretation?

A population parameter is a fixed, typically unknown numerical characteristic of an entire population (such as the true population mean μ or proportion p). A sample statistic is a numerical summary calculated from observed sample data (such as the sample mean x̄ or sample proportion p̂), used to estimate the unknown parameter. Sampling variability refers to the natural variation of sample statistics across different random samples drawn from the same population. Because of sampling variability, any single sample metric is subject to random error and rarely matches the true population parameter exactly. In metric interpretation, failing to account for this variability leads to mistaking noise for real change. Analysts must quantify estimation uncertainty using standard errors, confidence intervals, or hypothesis testing before concluding that an observed difference is genuine.

import numpy as np

# True population parameter (mean = 50, standard deviation = 10)
pop_mean = 50.0
pop_std = 10.0

# Draw multiple independent samples of size n=30
np.random.seed(42)
sample_means = [np.mean(np.random.normal(pop_mean, pop_std, size=30)) for _ in range(5)]

for i, sm in enumerate(sample_means, 1):
    print(f"Sample {i} Mean (Statistic): {sm:.2f} | Error: {sm - pop_mean:+.2f}")
Try answering this question with an AI coach

Intermediate questions

11What is a point estimator, and how do bias and variance affect its accuracy?

A point estimator is a statistic T(X) used to estimate a fixed population parameter theta. The number obtained from one observed sample is the point estimate. Bias is E[T] - theta over repeated samples from the assumed data-generating process; variance is E[(T - E[T])²]. Under squared-error loss, MSE(T) = Var(T) + Bias(T)². Thus an unbiased estimator can still be inaccurate if its variance is large, while a slightly biased estimator can have lower MSE by greatly reducing variance. Shrinkage is a common example: moving noisy estimates toward a reference introduces bias but can improve average squared error. These properties depend on the sampling model and sample size; they do not automatically address measurement error, selection bias or distribution shift. A point estimate should usually be accompanied by an uncertainty statement appropriate to the design.

Try answering this question with an AI coach

12How can you narrow a confidence interval for a population mean?

For independent observations under the usual assumptions, a two-sided mean interval is x-bar plus or minus a critical value times s/sqrt(n), using a t critical value when appropriate. More independent observations reduce standard error; roughly quadrupling n halves the standard-error component. Better measurement, a well-designed stratified sample or valid covariate adjustment can reduce variance while preserving the target estimand. Correlated or clustered observations supply less information than the same number of independent observations, so account for the design rather than treating every row as independent. Lowering the confidence level also narrows the interval, but explicitly sacrifices coverage and is not a free improvement. Do not discard inconvenient observations or choose the interval method after seeing the desired result. A narrow interval can still be centered on a biased estimate; representativeness and correct assumptions matter alongside precision.

Try answering this question with an AI coach

13Return the first streamed title for every user on each calendar day.

Derive each session's date in the reporting time zone. Rank rows with ROW_NUMBER() partitioned by user_id and that date, ordered by start time and a stable unique stream ID. Keep rank one, then look up the title. Define whether simultaneous starts should be reduced to one, as requested, or all returned by a different rule.

Try answering this question with an AI coach

14How would you design cohort cuts for an activation or retention investigation to ensure comparisons are not confounded by mix shifts or maturity truncation?

To design cohort cuts that avoid mix shifts and maturity truncation: 1. **Standardize Tenure Windows**: Align cohorts by relative tenure (e.g., Day 0, Day 7, Day 30 after signup/activation) rather than calendar dates to ensure fair lifecycle comparisons. 2. **Handle Maturity Truncation (Right-Censoring)**: Only evaluate cohorts that have fully matured through the observation window. Exclude or explicitly flag recent cohorts that have not had the full duration to complete the milestone. 3. **Mitigate Mix Shifts**: Segment cohorts across influential confounding dimensions (such as acquisition channel, platform, country, or user intent). If reporting an aggregate number, use standardization/post-stratification weighting so shifts in acquisition source mix do not distort the perceived retention trend.

WITH user_cohorts AS (
    SELECT 
        user_id,
        DATE_TRUNC('week', signup_time) AS cohort_week,
        signup_time,
        acquisition_channel
    FROM users
    -- Exclude cohorts that have not reached 7 full days of maturity
    WHERE signup_time <= CURRENT_DATE - INTERVAL '7 days'
),
user_activity AS (
    SELECT DISTINCT 
        c.user_id,
        c.cohort_week,
        c.acquisition_channel,
        1 AS retained_d7
    FROM user_cohorts c
    JOIN events e ON c.user_id = e.user_id
    WHERE e.event_time >= c.signup_time + INTERVAL '7 days'
      AND e.event_time < c.signup_time + INTERVAL '8 days'
)
SELECT 
    c.cohort_week,
    c.acquisition_channel,
    COUNT(c.user_id) AS cohort_size,
    COUNT(a.user_id) AS d7_active_users,
    ROUND(100.0 * COUNT(a.user_id) / COUNT(c.user_id), 2) AS d7_retention_pct
FROM user_cohorts c
LEFT JOIN user_activity a ON c.user_id = a.user_id
GROUP BY 1, 2
ORDER BY 1 DESC, 2;
Try answering this question with an AI coach

15During evaluation, your model achieves an unusually high metric like an AUC of 0.99, but performance plummets in shadow testing. How do you systematically isolate and verify target leakage?

When a model achieves an unrealistically high offline metric (e.g., AUC of 0.99) that plummets in live shadow testing, target leakage is the primary suspect. A systematic isolation and verification workflow includes: 1. Feature Importance & Attribution: Compute SHAP values, gain importances, or permutation importance to identify candidate features with dominant predictive power. 2. Single-Feature Models & Ablation Studies: Train simple 1-feature models (e.g., shallow decision trees or logistic regression) on individual suspicious features. If a single feature achieves near-perfect classification, it is likely leaking the target. Sequentially ablate suspect features and measure the drop in offline performance. 3. Temporal & Timestamp Lineage Audit: Check the exact creation/update timestamps of candidate features relative to the prediction cutoff timestamp. Verify whether the feature value could only be known after the target event occurred (e.g., `cancellation_reason` or `refund_status` populated upon churn/chargeback). 4. Data Lineage and Engineering Verification: Review the upstream data pipeline and table mutation logic (e.g., mutable tables updated in place vs append-only immutable logs) to verify when fields are populated.

from sklearn.metrics import roc_auc_score
from sklearn.tree import DecisionTreeClassifier

leakage_candidates = {}
for col in X_train.columns:
    clf = DecisionTreeClassifier(max_depth=2)
    clf.fit(X_train[[col]], y_train)
    preds = clf.predict_proba(X_test[[col]])[:, 1]
    auc = roc_auc_score(y_test, preds)
    if auc > 0.85:
        leakage_candidates[col] = auc

print("Candidate Leaky Features:", leakage_candidates)
Try answering this question with an AI coach

16How do you decide between standard K-Fold, Stratified K-Fold, and Group K-Fold cross-validation when evaluating structured real-world data?

The choice among standard K-Fold, Stratified K-Fold, and Group K-Fold depends on target distribution and row independence: 1. Standard K-Fold: Splits data into K approximately equal folds; scikit-learn KFold does not shuffle by default, so randomization must be explicitly enabled when appropriate. It assumes observations are independent and identically distributed (IID) and is typically used for continuous regression targets or well-balanced datasets. 2. Stratified K-Fold: Ensures each fold preserves the same percentage of target class labels as the complete dataset. It is useful for classification tasks, especially with class imbalance, to avoid folds containing too few or no minority class samples. 3. Group K-Fold: Ensures that distinct groups/entities (e.g., `user_id`, `patient_id`, `device_id`) do not appear in both training and validation folds simultaneously. When multiple observations come from the same entity, random row splitting can give an overly optimistic estimate for unseen-entity deployment because the model memorizes entity-specific traits rather than learning generalizable signals. Group K-Fold evaluates unseen entities. For future observations of known entities, use a chronology-aware split matching that task; combine group and time constraints when both apply.

from sklearn.model_selection import KFold, StratifiedKFold, GroupKFold, StratifiedGroupKFold

# Standard IID Regression:
cv_kfold = KFold(n_splits=5, shuffle=True, random_state=42)

# Imbalanced Classification (IID samples):
cv_strat = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

# Grouped entities (e.g., repeated patient visits):
cv_group = GroupKFold(n_splits=5)

# Grouped entities with target imbalance:
cv_strat_group = StratifiedGroupKFold(n_splits=5)
Try answering this question with an AI coach

17How do you choose between Logistic Regression, Gradient Boosted Decision Trees, and nonlinear neural architectures for tabular classification under latency and drift constraints?

Benchmark logistic regression, GBDTs and an appropriate neural baseline on representative out-of-time/grouped validation data and production hardware. LR gives inexpensive linear scoring and transparent coefficients but needs suitable encodings and interactions; extrapolation can still be confidently wrong under drift. GBDTs often perform well on tabular data, but native categorical/missing-value support depends on the implementation and configuration. Ordinary constant-leaf trees extrapolate poorly beyond training support; this is not a safety guarantee. Neural models can help with multimodal inputs, embeddings or sufficient data, but their latency and drift behavior depend on architecture and deployment. Compare end-to-end p95/p99 latency including feature retrieval, calibration, memory, maintenance, segment performance and robustness. No model family universally guarantees a millisecond SLA or drift resilience.

decision_matrix = {
    "Logistic Regression": {"Latency": "<1ms (Ultra-low)", "Drift Behavior": "Linear extrapolation", "Tabular Baseline": "Moderate (needs feature engineering)"},
    "GBDT (XGB/LightGBM)": {"Latency": "1-15ms (Fast)",      "Drift Behavior": "Leaf clamping (no extrapolation)", "Tabular Baseline": "State of the Art"},
    "Tabular Neural Net":  {"Latency": "10-50ms+ (Higher)",    "Drift Behavior": "Nonlinear extrapolation", "Tabular Baseline": "Competitive / High tuning cost"}
}
for model, traits in decision_matrix.items():
    print(f"{model}: Latency={traits['Latency']}, Tabular Perf={traits['Tabular Baseline']}")
Try answering this question with an AI coach

Advanced questions

18You can sample from a proposal distribution but need an average under a different target distribution. How does importance sampling work, and when can it fail?

If X is sampled from proposal density q but the desired expectation is under normalized target p, use weights w(X) = p(X)/q(X). Then the average of w(Xi) f(Xi) estimates E_p[f(X)], provided q covers the target's relevant support and the expectation exists. If p is known only up to a constant, use the self-normalized ratio sum(wi f(Xi))/sum(wi); it is generally biased at finite sample size but can be consistent under suitable conditions. The method fails when q assigns zero probability where important target mass exists, and becomes unstable when a few enormous weights dominate because the proposal has poor overlap or tails. Inspect weight concentration and effective sample size, use a better proposal or mixtures, and assess uncertainty. More samples cannot repair a fundamental support mismatch.

Try answering this question with an AI coach

19How would you architect a centralized semantic layer across an enterprise data warehouse to ensure consistent business metric definitions across disparate analytics teams?

Architecting a centralized semantic layer across an enterprise data warehouse requires establishing a declarative, code-based metric definition layer (such as MetricFlow/dbt Semantic Layer, Cube, or LookML) that decouples business logic from physical storage and downstream consumption tools (BI platforms, Python/R notebooks, APIs). The core architecture defines entities, dimensions, measures, and derived metrics in version-controlled repositories (Git) to provide a single source of truth and enforce metric consistency across teams. To support multi-tenancy and governance across disparate business units, a federated governance model should be used: core enterprise KPIs (e.g., ARR, Active Users) are owned by a central data governance team, while domain-specific metrics are managed by decentralized domain teams via isolated semantic models with CI/CD validation. The semantic layer then exposes standardized query interfaces (SQL, GraphQL, REST) with unified role-based access control and caching/pre-aggregation to maintain performance and consistency.

semantic_model:
  name: orders
  node_relation:
    alias: fct_orders
  dimensions:
    - name: order_date
      type: time
      type_params:
        time_granularity: day
    - name: country
      type: categorical
  measures:
    - name: total_revenue
      expr: revenue_usd
      agg: sum
    - name: distinct_buyers
      expr: user_id
      agg: count_distinct

metrics:
  - name: average_order_value
    description: "Governed metric for AOV across all BI tools"
    type: ratio
    type_params:
      numerator: total_revenue
      denominator: distinct_buyers
Try answering this question with an AI coach

20In a two-sided marketplace (such as rideshare or e-commerce), how would you design an experiment to evaluate a matching algorithm change while accounting for supply-demand cannibalization and spatial-temporal interference?

Define whether the target is the effect of full rollout on the marketplace or a direct effect at partial adoption. Ordinary user-level A/B assignment may estimate neither cleanly: treatment changes available capacity and therefore control outcomes. Map the shared resource and choose clusters that largely contain competition, such as geographic markets, or randomized market-time switchbacks when the market cannot be split. Balance time/market factors, select periods long enough for relevant dynamics, and include washout or explicitly model carryover; check leakage across cluster boundaries. Measure total completed transactions, value, waiting time, utilization and outcomes on both sides, not only treated-user conversion. Use inference at the randomized cluster/time-block level with appropriate dependence handling and power calculations. A saturation design can help estimate spillovers. Validate assumptions and report the exposure regime, since a partial-market result may not extrapolate to full deployment.

import pandas as pd
import numpy as np

def generate_switchback_schedule(n_days=14, window_minutes=60, washout_minutes=15):
    total_windows = int((n_days * 24 * 60) / window_minutes)
    np.random.seed(42)
    treatments = np.random.binomial(1, 0.5, size=total_windows)
    schedule = []
    for i, trt in enumerate(treatments):
        start_min = i * window_minutes
        eval_start_min = start_min + washout_minutes
        end_min = (i + 1) * window_minutes
        schedule.append({
            'window_id': i,
            'treatment': trt,
            'start_min': start_min,
            'eval_start_min': eval_start_min,
            'end_min': end_min
        })
    return pd.DataFrame(schedule)
Try answering this question with an AI coach

Practice Data Scientist interviews on your phone

Answer out loud and get AI feedback in the Android app.

Get EngineerSpeak on Google Play
Scan to download