Skip to content

Data Scientist Interview Questions & Answers

40 questions for Data Scientist interviews — 4 easy, 33 medium, 3 hard.

About the Data Scientist role

A data scientist turns business questions into data analysis and predictive models, from pulling data with SQL to building, validating and explaining models. Interviews test Python and SQL coding, statistics and experiment design, core machine learning, and case studies where you frame a problem, pick metrics and communicate results to non-technical stakeholders. Expect a take-home or live coding round plus a project deep dive.

Python and Pandas SQL with window functions Hypothesis testing and A/B tests Supervised machine learning Stakeholder communication
Solved for this roleStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

Why is XGBoost so popular?

Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
02

After joining orders with a promotions table, total revenue doubled. What went wrong?

Save to ▾
Show answer
The join created duplicate order rows, because some orders match more than one promotion row, so each amount is counted several times. Check by comparing COUNT(*) with COUNT(DISTINCT order_id) after the join. Fix it by aggregating the promotions table to one row per order first, picking one promotion with ROW_NUMBER, or summing revenue before the join. Always check row counts after every join.
03

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
04

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
05

Explain the basic idea of an ARIMA model.

Save to ▾
Show answer
ARIMA models a time series using three parts. AR, autoregressive, uses past values of the series. I, integrated, differences the series d times to remove trend and make it stationary. MA, moving average, uses past forecast errors. You choose p, d and q using ACF and PACF plots or information criteria like AIC. SARIMA adds seasonal terms. ARIMA works well for single, fairly stable series but struggles with many external drivers.
06

Write Pandas code to read a large CSV in chunks and compute total sales per city.

Save to ▾
Show answer
# process 1 million rows at a time import pandas as pd totals = {} for chunk in pd.read_csv('sales.csv', usecols=['city', 'amount'], chunksize=1_000_000): part = chunk.groupby('city')['amount'].sum() for city, amt in part.items(): totals[city] = totals.get(city, 0) + amt result = pd.Series(totals).sort_values(ascending=False)
07

A key metric dropped 8 percent week over week. How do you check whether it is real?

Save to ▾
Show answer
First rule out data issues: tracking changes, pipeline delays, missing partitions or a changed metric definition. Then compare with the same week last year and look for holidays or seasonality. Check normal weekly variation to see if 8 percent is unusual. Break the drop down by platform, region, app version and user type to find where it is concentrated. Finally, check releases, campaigns or outages that happened that week.
08

You want to test a new pricing algorithm in a two-sided marketplace where buyers and sellers interact. Why is user-level randomisation a problem and what would you do?

Save to ▾
Show answer
Treated and control buyers compete for the same sellers' supply, so a treatment that makes treated buyers buy more takes inventory from control buyers, exaggerating the measured lift. Use designs that limit interference: switchback tests that alternate the whole market between variants over time slots, or randomise by city or region. Analyse at the switch or cluster level with appropriate variance, and accept that these tests need longer to reach power.
09

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
10

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
11

Pandas: compute a 7-day rolling average of daily sales for each store.

Save to ▾
Show answer
# df has columns: store, date, sales df['date'] = pd.to_datetime(df['date']) df = df.sort_values(['store', 'date']) df['sales_7d_avg'] = ( df.groupby('store')['sales'] .transform(lambda s: s.rolling(7, min_periods=1).mean()) )
12

What is the Central Limit Theorem?

Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
13

What is the difference between a Pandas Series and a DataFrame?

Save to ▾
Show answer
A Series is a one-dimensional labelled array: one column of values with an index. A DataFrame is a two-dimensional table made of several Series that share the same index, and each column can have its own dtype. Selecting one column, like df['price'], gives you a Series. Selecting with a list, like df[['price']], gives you a DataFrame. Many methods work on both, but the output shape is different.
14

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
15

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
16

Tell me about a time you had to deliver data under an urgent deadline.

Save to ▾
Show answer
Situation: the leadership team needed festive-sale numbers by city for a 9 am review, and the dashboard pipeline had failed overnight. Task: deliver accurate numbers in three hours. Action: I queried the raw orders tables directly, reused validated logic from the dashboard SQL, cross-checked totals with finance's daily figure and flagged two cities with partial data. Result: the review went ahead on time, and I later added pipeline failure alerts.
17

What is the difference between semantic, instance and panoptic segmentation?

Save to ▾
Show answer
Semantic segmentation gives each pixel a class, such as road or car, but does not separate two cars. Instance segmentation separates individual objects of countable classes, giving each car its own mask. Panoptic segmentation combines both: every pixel gets a class, and countable objects also get an instance ID, while background stuff like sky stays semantic. Autonomous driving and robotics often need panoptic or instance output.
18

Describe a production incident with a model and how you handled it.

Save to ▾
Show answer
Situation: one morning our recommendation model started showing the same five products to all users. Task: restore service and find the cause. Action: I rolled back to the previous model version within 20 minutes, then traced the issue to an upstream table that had arrived empty, so all user features were defaults. Result: we added data volume checks before scoring and a blameless postmortem. Rollback readiness saved us that day.
19

What is the difference between hard voting and soft voting in ensembles?

Save to ▾
Show answer
In hard voting each model predicts a class and the majority wins. In soft voting each model gives class probabilities, they are averaged, and the class with the highest average wins. Soft voting usually works better because it uses each model's confidence, but it needs calibrated probabilities from all models. Hard voting is simpler and works even with models that only output labels.
20

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
21

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
22

What is the difference between a star schema and a snowflake schema?

Save to ▾
Show answer
A star schema has a central fact table, like sales with amounts and foreign keys, surrounded by denormalised dimension tables such as product, customer and date. A snowflake schema normalises dimensions further, for example product links to a separate category table. Star schemas need fewer joins and are faster and simpler for analysts. Snowflake schemas save storage and reduce duplication but make queries more complex.
23

How do you evaluate clustering when you have no labels?

Save to ▾
Show answer
Use internal metrics: the silhouette score compares how close a point is to its own cluster versus the nearest other cluster, and the Davies-Bouldin index measures cluster overlap. The elbow method looks at within-cluster variance. But the real test is usefulness: are clusters stable across random seeds and samples, can the business describe them, and do they behave differently on outcomes like spend or churn?
24

You assign values to a filtered DataFrame and Pandas shows a SettingWithCopyWarning. What is going on and how do you fix it?

Save to ▾
Show answer
The warning appears when you assign values to something that may be a copy of a slice instead of the original DataFrame, for example df[df.age > 30]['flag'] = 1. The original may not change. Fix it by using a single .loc call, like df.loc[df.age > 30, 'flag'] = 1, or by taking an explicit .copy() when you really want a separate DataFrame. Copy-on-write in newer Pandas versions makes this behaviour more predictable.
25

The business asks you to pick a decision threshold for a churn model. How do you choose it?

Save to ▾
Show answer
The default 0.5 is rarely right. I would get the cost of each outcome: the value of saving a churner, the cost of a retention offer, and the team's capacity to contact customers. Then I compute expected profit or precision and recall at many thresholds on validation data and pick the one that maximises value within capacity. I would also check that the chosen threshold stays stable over recent months.
26

Your credit model has good overall AUC but performs much worse for applicants from one region. What do you do?

Save to ▾
Show answer
First confirm with per-segment metrics and enough samples, since small groups are noisy. Then check why: fewer training examples from that region, different feature distributions, missing data or labels that reflect past biased decisions. Fixes include collecting more data, reweighting, segment-aware features or a separate calibration. Also review fairness and regulatory requirements, and agree with risk and compliance teams on acceptable performance gaps before launch.
27

What is the difference between a subquery and a correlated subquery?

Save to ▾
Show answer
A normal subquery runs once on its own and its result is used by the outer query, for example WHERE price > (SELECT AVG(price) FROM products). A correlated subquery refers to columns of the outer query, so it is logically evaluated once per outer row, for example comparing each product with its own category average. Correlated subqueries can be slow; joins or window functions are usually faster alternatives.
28

Tell me about a time you disagreed with a stakeholder about which metric to optimise.

Save to ▾
Show answer
Situation: marketing wanted the lead model judged on overall accuracy. Task: agree on a metric that matched the goal. Action: I showed that accuracy rewarded predicting no conversion for everyone, then proposed precision in the top 1,000 leads per week, which matched the sales team's call capacity, with a simple chart. Result: they agreed, and the model with the better top-1,000 precision added 18 percent more conversions.
29

Tell me about a time your model did not perform as expected after deployment.

Save to ▾
Show answer
Situation: my demand forecasting model had 8 percent error offline, but 20 percent in the first month live. Task: find out why quickly. Action: I compared live inputs with training data and found a promotions feature arrived a day late in production, so the model saw zeros. I added a data freshness check and a fallback. Result: error returned to 9 percent. Since then I always test with production-like pipelines before launch.
30

What is DBSCAN and when is it better than K-means?

Save to ▾
Show answer
DBSCAN is a density-based clustering algorithm. It groups points that have at least min_samples neighbours within distance eps, and marks isolated points as noise. Unlike K-means, it does not need the number of clusters, finds clusters of any shape, and handles outliers. It struggles when clusters have very different densities and in high dimensions. It suits location data, like finding delivery hotspots from GPS points.
31

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
32

What is bootstrapping in statistics?

Save to ▾
Show answer
Bootstrapping estimates the uncertainty of a statistic by resampling your data with replacement many times, computing the statistic on each resample, and looking at the spread of results. It gives confidence intervals for things with no simple formula, like the median, a ratio or a model metric such as AUC. It needs no normality assumption, but it relies on the sample being representative and can be slow on very large data.
33

Your sales forecast scores well in k-fold cross-validation but fails in production. What could be wrong with the validation?

Save to ▾
Show answer
Random k-fold mixes future and past rows, so the model trains on data from after the period it predicts. That leaks information and inflates scores. Use time-based splits instead: train on an expanding or rolling window and validate on the next period, like TimeSeriesSplit in scikit-learn. Leave a gap between train and validation when features use lagged values, so the test reflects real forecasting conditions.
34

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
35

Write scikit-learn code to get precision, recall and a confusion matrix at a custom threshold of 0.3.

Save to ▾
Show answer
from sklearn.metrics import confusion_matrix, precision_score, recall_score proba = model.predict_proba(X_test)[:, 1] pred = (proba >= 0.3).astype(int) print(confusion_matrix(y_test, pred)) print('precision', precision_score(y_test, pred)) print('recall', recall_score(y_test, pred))
36

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
37

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
38

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
39

Pandas: convert wide monthly columns into a long format table.

Save to ▾
Show answer
# wide: id, jan, feb, mar -> long: id, month, value long_df = df.melt( id_vars=['id'], value_vars=['jan', 'feb', 'mar'], var_name='month', value_name='value' )
40

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.

Frequently asked questions

What does a Data Scientist do?

A data scientist turns business questions into data analysis and predictive models, from pulling data with SQL to building, validating and explaining models. Interviews test Python and SQL coding, statistics and experiment design, core machine learning, and case studies where you frame a problem, pick metrics and communicate results to non-technical stakeholders. Expect a take-home or live coding round plus a project deep dive.

Which skills are tested in a Data Scientist interview?

Expect questions on Python and Pandas, SQL with window functions, Hypothesis testing and A/B tests, Supervised machine learning, Stakeholder communication. Most rounds also ask you to explain a project and solve one practical problem live.

How do I prepare for a Data Scientist interview?

Revise Python for Data Science, Statistics and Probability, Machine Learning, SQL for Data Science first using the topic sheets, practise the questions on this page aloud, then do one full mock interview to practise timing.