🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Statistical Thinking: Applying Statistics to Real Business Problems

Data Scientist Role InterviewStatistical Thinking & Inference⭐ Premium
📊

Asked at Netflix & Google

Statistical Thinking

Applying Statistics to Real Business Problems

The Interview Question

"Netflix sees that users who watch more foreign content have higher retention. Does this mean foreign content causes higher retention? How would you investigate this?"

This question tests whether you can distinguish correlation from causation and apply statistical thinking to business problems.


Why Companies Ask This

â„šī¸

Netflix and Google need data scientists who don't just run statistical tests, but who think statistically about business problems. They need to know you understand the limitations of data and can draw valid conclusions.

Interviewers evaluate:

  1. Correlation vs. Causation — Do you understand the distinction?
  2. Experimental Design — Can you design valid studies?
  3. Statistical Methods — Do you know which method to apply when?
  4. Practical Significance — Do you distinguish statistical from practical significance?
  5. Uncertainty Quantification — Can you communicate uncertainty clearly?

The Statistical Thinking Framework

1. Observation → Hypothesis

  • What pattern do you observe?
  • What's your initial hypothesis?
  • What are alternative explanations?

2. Data → Evidence

  • What data would help distinguish between explanations?
  • What confounding variables might exist?
  • What biases might be present?

3. Analysis → Inference

  • What statistical method is appropriate?
  • What are the assumptions?
  • What do the results actually mean?

4. Conclusion → Action

  • What can we conclude?
  • What are the limitations?
  • What should we do next?

Example: Foreign Content & Retention

Observation

"Users who watch foreign content have 23% higher retention than those who don't."

Initial Hypothesis

"Foreign content might be causing higher retention by providing more diverse content options."

Alternative Explanations

python
alternatives = {
    'causal': 'Foreign content directly improves retention',
    'self_selection': 'More engaged users watch more foreign content',
    'confounding': 'A third factor (e.g., curiosity, open-mindedness) causes both',
    'reverse_causation': 'Users who plan to stay longer are more likely to explore foreign content',
    'survivorship': 'Users who churn early never discover foreign content',
}

# Key question: Which explanation is most likely?
# How would you distinguish between them?

Investigating with Observational Data

python
import pandas as pd
import numpy as np
from scipy import stats

def observational_analysis(users_df, viewing_df):
    """
    Analyze the relationship between foreign content and retention
    using observational data (no experiment).
    """
    # Merge user data with viewing behavior
    user_viewing = viewing_df.groupby('user_id').agg(
        foreign_content_hours=('content_type', lambda x: (x == 'foreign').sum()),
        total_hours=('hours_watched', 'sum'),
        foreign_ratio=('content_type', lambda x: (x == 'foreign').mean()),
    ).reset_index()
    
    analysis_df = users_df.merge(user_viewing, on='user_id')
    
    # 1. Basic correlation
    correlation = analysis_df[['foreign_ratio', 'retention_90d']].corr().iloc[0, 1]
    print(f"Correlation between foreign content ratio and retention: {correlation:.3f}")
    
    # 2. Controlling for confounders
    # User tenure (longer-tenured users may watch more foreign content)
    tenure_groups = pd.cut(analysis_df['tenure_months'], bins=[0, 3, 6, 12, 24, 999])
    
    controlled_correlations = []
    for group in tenure_groups.unique():
        group_data = analysis_df[tenure_groups == group]
        if len(group_data) > 100:
            corr = group_data[['foreign_ratio', 'retention_90d']].corr().iloc[0, 1]
            controlled_correlations.append({
                'tenure_group': group,
                'correlation': corr,
                'n_users': len(group_data),
            })
    
    # 3. Multiple regression
    import statsmodels.api as sm
    
    X = analysis_df[['foreign_ratio', 'tenure_months', 'total_hours', 
                     'account_age_days', 'plan_price']]
    X = sm.add_constant(X)
    y = analysis_df['retention_90d']
    
    model = sm.OLS(y, X).fit()
    print(model.summary())
    
    # 4. Propensity score matching
    # Match users who watch foreign content with similar users who don't
    from sklearn.linear_model import LogisticRegression
    from sklearn.neighbors import NearestNeighbors
    
    # Estimate propensity scores
    X_prop = analysis_df[['tenure_months', 'total_hours', 
                          'account_age_days', 'plan_price']]
    treatment = analysis_df['foreign_ratio'] > 0.5
    
    ps_model = LogisticRegression()
    ps_model.fit(X_prop, treatment)
    propensity_scores = ps_model.predict_proba(X_prop)[:, 1]
    
    # Match treated and control users
    treated_idx = np.where(treatment)[0]
    control_idx = np.where(~treatment)[0]
    
    nn = NearestNeighbors(n_neighbors=1)
    nn.fit(propensity_scores[control_idx].reshape(-1, 1))
    
    distances, matches = nn.kneighbors(
        propensity_scores[treated_idx].reshape(-1, 1)
    )
    
    # Calculate matched treatment effect
    matched_control_idx = control_idx[matches.flatten()]
    treatment_effect = (
        analysis_df.iloc[treated_idx]['retention_90d'].mean() -
        analysis_df.iloc[matched_control_idx]['retention_90d'].mean()
    )
    
    return {
        'raw_correlation': correlation,
        'controlled_correlations': controlled_correlations,
        'regression_coefficient': model.params['foreign_ratio'],
        'propensity_matched_effect': treatment_effect,
    }

The observational code above produces a ladder of estimates, and the interview answer is the pattern across the ladder. Suppose the raw correlation between foreign-content share and 90-day retention is 0.28. After stratifying by tenure, the within-stratum correlations fall to 0.05–0.09, which already suggests confounding: longer-tenured users both watch more foreign titles and naturally retain better. The regression coefficient on foreign_ratio shrinks to 0.03 once tenure, total hours, and plan price enter the model, and the propensity-matched estimate lands at 0.04 with a bootstrap interval of roughly 0.01 to 0.07. The honest conclusion: most of the raw gap was selection, but a small positive association survives adjustment. Because that residual could still come from unmeasured traits such as language skill or travel interest, the next step is a randomized encouragement design — randomly surface foreign titles to a treatment group and measure the retention delta on that instrumented exposure.


Choosing the Test Before You Run It

Interviewers watch whether you match the test to the data shape. Continuous metric, two groups, roughly symmetric residuals: Welch's t-test. Heavily skewed metric like watch time: log-transform or reach for Mann-Whitney U, and say that the U test answers a distribution question rather than a mean difference. Categorical outcome: chi-squared on the contingency table, with Fisher's exact test when any expected cell drops below five. Small samples: report the bootstrap confidence interval and treat the parametric p-value as secondary. Each choice has an assumption you should name out loud — equal variance, independence of observations, adequate expected counts — and the rubric rewards stating which assumption is most fragile in your dataset.


Key Statistical Concepts for Interviews

Hypothesis Testing

python
from scipy import stats

def hypothesis_test_example():
    """
    Common hypothesis testing scenarios in interviews.
    """
    
    # Scenario 1: A/B test result
    control_conversions = [120, 115, 118, 122, 119]
    treatment_conversions = [135, 128, 132, 140, 133]
    
    t_stat, p_value = stats.ttest_ind(control_conversions, treatment_conversions)
    print(f"A/B Test: t={t_stat:.3f}, p={p_value:.4f}")
    
    # Scenario 2: Chi-squared test for categorical data
    # Does payment method differ by user segment?
    observed = np.array([
        [450, 150],  # Premium users: credit, paypal
        [300, 200],  # Free users: credit, paypal
    ])
    
    chi2, p_value, dof, expected = stats.chi2_contingency(observed)
    print(f"Chi-squared: Ī‡Â˛={chi2:.3f}, p={p_value:.4f}")
    
    # Scenario 3: Non-parametric test (when data isn't normal)
    # Mann-Whitney U test
    control = [12, 15, 18, 22, 25, 28, 31, 35, 40, 50]
    treatment = [18, 22, 25, 28, 32, 35, 40, 45, 52, 60]
    
    u_stat, p_value = stats.mannwhitneyu(control, treatment, alternative='less')
    print(f"Mann-Whitney U: U={u_stat:.3f}, p={p_value:.4f}")

Bayesian Thinking

python
import numpy as np

def bayesian_ab_test(control_conversions, control_trials,
                     treatment_conversions, treatment_trials,
                     n_simulations=100000):
    """
    Bayesian A/B test using Monte Carlo simulation.
    """
    # Prior: Beta(1, 1) = uniform prior
    alpha_prior = 1
    beta_prior = 1
    
    # Posterior for control
    alpha_control = alpha_prior + control_conversions
    beta_control = beta_prior + (control_trials - control_conversions)
    
    # Posterior for treatment
    alpha_treatment = alpha_prior + treatment_conversions
    beta_treatment = beta_prior + (treatment_trials - treatment_conversions)
    
    # Sample from posteriors
    control_samples = np.random.beta(alpha_control, beta_control, n_simulations)
    treatment_samples = np.random.beta(alpha_treatment, beta_treatment, n_simulations)
    
    # Probability that treatment is better
    prob_treatment_better = (treatment_samples > control_samples).mean()
    
    # Expected loss (risk of choosing treatment when control is better)
    expected_loss = np.mean(
        np.maximum(control_samples - treatment_samples, 0)
    )
    
    # Credible interval for the difference
    diff_samples = treatment_samples - control_samples
    ci_lower = np.percentile(diff_samples, 2.5)
    ci_upper = np.percentile(diff_samples, 97.5)
    
    return {
        'prob_treatment_better': prob_treatment_better,
        'expected_loss': expected_loss,
        'credible_interval': (ci_lower, ci_upper),
        'control_rate': alpha_control / (alpha_control + beta_control),
        'treatment_rate': alpha_treatment / (alpha_treatment + beta_treatment),
    }

# Example
result = bayesian_ab_test(
    control_conversions=120, control_trials=1000,
    treatment_conversions=140, treatment_trials=1000
)
print(f"P(Treatment > Control) = {result['prob_treatment_better']:.3f}")
print(f"95% Credible Interval: [{result['credible_interval'][0]:.4f}, {result['credible_interval'][1]:.4f}]")

The simulation returns a decision-ready number: the probability treatment beats control and the expected loss from shipping a worse variant. Teams that adopt Bayesian reporting usually set rules such as ship when the probability of improvement exceeds 0.95 and the expected loss stays under a tenth of a percentage point of the metric. The prior matters least once you have thousands of trials, but with early data the uniform Beta(1,1) prior is a safe default; an informative prior built from last quarter's experiments can cut the sample you need in half, provided you can defend the prior to a skeptical audience.

Causal Inference

python
def causal_inference_methods():
    """
    Overview of causal inference methods for interviews.
    """
    
    methods = {
        'randomized_experiment': {
            'when': 'When you can randomize treatment assignment',
            'assumption': 'Randomization eliminates confounding',
            'example': 'A/B testing a new feature',
        },
        'propensity_score_matching': {
            'when': 'When you have observational data and can estimate treatment probability',
            'assumption': 'Selection on observables (unconfoundedness)',
            'example': 'Estimating effect of marketing campaign',
        },
        'difference_in_differences': {
            'when': 'When you have pre/post data for treated and control groups',
            'assumption': 'Parallel trends (treatment and control would follow same trend without treatment)',
            'example': 'Evaluating policy change in one region',
        },
        'regression_discontinuity': {
            'when': 'When treatment is assigned based on a threshold',
            'assumption': 'Units near threshold are comparable',
            'example': 'Effect of financial aid on graduation (aid given above income threshold)',
        },
        'instrumental_variables': {
            'when': 'When you have a variable that affects treatment but not outcome directly',
            'assumption': 'Exclusion restriction (instrument only affects outcome through treatment)',
            'example': 'Effect of education on earnings (using distance to college as instrument)',
        },
    }
    
    return methods

Common Statistical Mistakes

âš ī¸

These mistakes are red flags in interviews:

1. P-Hacking

python
# BAD: Testing multiple hypotheses and reporting only significant ones
results = {}
for metric in ['retention', 'engagement', 'satisfaction', 'churn']:
    _, p = stats.ttest_ind(treatment[metric], control[metric])
    results[metric] = p

# If you only report the significant ones, that's p-hacking

# GOOD: Pre-specify primary hypothesis and correct for multiple comparisons
from statsmodels.stats.multitest import multipletests

p_values = [results[m] for m in results]
reject, corrected_p, _, _ = multipletests(p_values, method='bonferroni')

2. Ignoring Effect Size

python
# BAD: "p < 0.05, so it's significant!"
# GOOD: "p < 0.05, with an effect size of 2% improvement (95% CI: 0.5% to 3.5%)"

# Effect size matters more than p-value for business decisions
def report_with_effect_size(treatment_mean, control_mean, treatment_std, control_std, n):
    """
    Report results with effect size and practical significance.
    """
    diff = treatment_mean - control_mean
    pooled_std = np.sqrt(((n-1)*treatment_std**2 + (n-1)*control_std**2) / (2*n-2))
    cohens_d = diff / pooled_std
    
    return {
        'absolute_difference': diff,
        'relative_difference': diff / control_mean,
        'cohens_d': cohens_d,
        'practical_significance': abs(cohens_d) > 0.2,  # Small effect threshold
    }

3. Confusing Statistical with Practical Significance

python
# Example: Large sample can make tiny effects "significant"
# With 1 million users, a 0.01% improvement might be p < 0.001
# But is it worth the engineering effort?

def is_practically_significant(effect_size, cost_of_implementation, 
                                value_per_user, n_users):
    """
    Determine if an effect is practically significant.
    """
    total_value = effect_size * value_per_user * n_users
    roi = total_value / cost_of_implementation
    
    return {
        'total_value': total_value,
        'roi': roi,
        'recommendation': 'Implement' if roi > 2 else 'Do not implement',
    }

Quiz: Test Your Understanding


Common Mistakes

Reading a correlation as a causal effect

Fix: List self-selection, confounding, and reverse-causation explanations first, then show which adjustment moves the estimate and by how much

Running a t-test on heavily skewed data without comment

Fix: Check the residuals; log-transform or use Mann-Whitney U and say which question the alternative test answers

Reporting p below 0.05 without an effect size or interval

Fix: Give the point estimate, a confidence or credible interval, and the practical threshold the effect must clear to be worth shipping

Key Takeaways

  • Correlation-versus-causation answers start by generating rival explanations — selection, confounding, reverse causation — then design evidence that separates them
  • Stratification, regression adjustment, and propensity matching form a ladder: if the estimate collapses after the first control, the raw gap was mostly selection
  • Match the test to the data: Welch t-test for symmetric continuous metrics, Mann-Whitney for skewed ones, chi-squared for categorical outcomes
  • Bayesian A/B reporting converts posteriors into the probability treatment is better and the expected loss, which map directly to ship, hold, and kill rules

Related Topics

🔒

Premium Content

Statistical Thinking: Applying Statistics to Real Business Problems

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-17

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement