Data Science Interview Questions for 7 Years Experience
40 questions with answers for candidates with 7 years of experience — 15 medium, 25 hard.
What interviewers expect: 7 years experience
At seven years, interviews look for lead or staff level thinking. You should design data science roadmaps, platform choices and team processes, and explain how your work changed business metrics. Expect questions on building teams, setting evaluation standards, governance and responsible AI, and when to use GenAI versus classic ML across a portfolio of use cases.
This set is weighted towards A/B Testing & Experimentation (6), Statistics and Probability (6), Computer Vision (4), Time Series & Forecasting (4).
Data science strategy Platform and tooling choices Team building Responsible AI
Solved at this levelStart 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
How do one-stage and two-stage object detectors differ?
Two-stage detectors, like Faster R-CNN, first propose candidate regions and then classify and refine each one, which gives strong accuracy, especially for small objects, but is slower. One-stage detectors, like YOLO and SSD, predict boxes and classes directly over a dense grid in a single pass, making them fast enough for real-time video. Modern one-stage models have closed most of the accuracy gap, so they dominate edge and video use cases.
02
What is Bayesian A/B testing and how are its results reported?
Bayesian A/B testing starts with a prior on each variant's metric, updates it with observed data and produces a posterior distribution. Instead of a p-value, you report things like the probability that treatment beats control, say 94 percent, and the expected loss if you choose the wrong variant. Business teams find this easier to interpret. Priors must be chosen sensibly, and continuous monitoring still needs discipline about decision rules.
03
What should you log for a production prediction service?
For each request, log a request ID, timestamp, model version, input features or a hash of them, the prediction and score, and latency. Log errors and fallback use separately. Do not log raw personal data unless needed and allowed; mask it. Aggregate these logs into dashboards for traffic, latency percentiles, error rate and score distribution. Joining logged predictions with later outcomes gives the data for monitoring and retraining.
04
What is hierarchical forecasting and why is reconciliation needed?
Hierarchical forecasting produces forecasts at several levels, such as SKU, store, city and national totals. If you forecast each level independently, the store forecasts will not add up to the city forecast. Reconciliation adjusts them to be consistent. Bottom-up sums the lowest level, top-down splits the total by proportions, and methods like MinT combine all levels optimally. Consistent numbers matter because finance, supply chain and stores plan from different levels.
05
You have 50,000 unlabelled images and budget to label only 3,000. How do you use the budget well?
Do not pick 3,000 at random. Label a small diverse seed set, using embedding clustering to cover variety, and train a first model. Then use active learning: label the images the model is least confident about or that disagree across models. Use semi-supervised methods like pseudo-labelling high-confidence images, or self-supervised pretraining on all 50,000. Keep a randomly sampled test set so evaluation stays unbiased.
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
07
CNN vs RNN vs Transformer — what is the difference?
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
09
Your feature computation on millions of rows uses only one CPU core. Would you use threads or processes to speed it up?
Because of the GIL, threads in CPython do not run Python bytecode in parallel. Threads are fine for I/O-bound work like calling APIs or reading many files. For CPU-bound work like feature computation on chunks, multiprocessing or joblib runs separate processes on separate cores. The cost is process start-up time and copying data between processes. Many NumPy and Pandas operations already release the GIL internally, so measure before adding complexity.
10
Write a Python function to split a long text into overlapping chunks by word count for a RAG index.
This is training-serving skew. The feature might be computed from data that arrives later, like final order status. First confirm exactly when each feature is available in production. Rebuild the training set using point-in-time values, as they were at prediction time, or drop the feature. A feature store with point-in-time joins and the same feature code for training and serving prevents this. Expect offline scores to drop, but they become honest.
12
Tell me about a GenAI project you built and what you learned from it.
Situation: our HR team answered the same leave and policy questions daily. Task: build an internal assistant in six weeks. Action: I built a RAG pipeline over policy PDFs, added citations, created a 150-question evaluation set with HR, and iterated on chunking and reranking. Result: answer accuracy reached 91 percent and HR queries dropped by 40 percent. I learned that the evaluation set mattered more than the choice of model.
13
What is positional encoding in transformers and why is it needed?
Self-attention treats input tokens as a set, so without extra information it cannot tell word order: dog bites man and man bites dog look the same. Positional encoding adds position information to each token embedding. The original transformer used fixed sine and cosine patterns; BERT learned position embeddings; many modern LLMs use rotary embeddings, which encode relative positions and extend better to longer contexts.
14
What is the difference between recursive and direct multi-step forecasting?
In recursive forecasting you train a one-step model and feed each prediction back as an input to predict the next step, so errors compound over the horizon. In direct forecasting you train a separate model for each horizon, such as one for t+1 and another for t+7, which avoids compounding but costs more and may give inconsistent forecasts. Hybrid and multi-output approaches sit in between and are common in production.
15
Tell me about a time you disagreed with a stakeholder about which metric to optimise.
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.
16
Describe a project where you worked with very little labelled data.
Situation: we had to classify 50,000 support tickets into 12 categories with only 600 labelled. Task: reach usable accuracy in a month. Action: I used a pretrained sentence embedding model with logistic regression, then active learning to pick the most uncertain tickets for agents to label in short daily batches. Result: with 2,000 labels we reached 86 percent macro F1. I learned that smart labelling beats waiting for perfect data.
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
18
Write SQL to compute week-1 retention by signup week.
WITH signups AS (
SELECT user_id, DATE_TRUNC('week', signup_date) AS cohort, signup_date
FROM users
), active AS (
SELECT DISTINCT s.user_id, s.cohort
FROM signups s
JOIN events e ON e.user_id = s.user_id
AND e.event_date >= s.signup_date + INTERVAL '7 day'
AND e.event_date < s.signup_date + INTERVAL '14 day'
)
SELECT s.cohort, COUNT(*) AS users,
ROUND(100.0 * COUNT(a.user_id) / COUNT(*), 1) AS week1_retention_pct
FROM signups s
LEFT JOIN active a ON a.user_id = s.user_id
GROUP BY s.cohort
ORDER BY s.cohort;
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
21
Write SQL to find users who logged in on at least three consecutive days.
WITH d AS (
SELECT DISTINCT user_id, CAST(login_at AS DATE) AS day
FROM logins
),
g AS (
SELECT user_id, day,
day - CAST(ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) AS INT) AS grp
FROM d
)
SELECT DISTINCT user_id
FROM g
GROUP BY user_id, grp
HAVING COUNT(*) >= 3;
-- date minus row number is constant within a streak (PostgreSQL syntax)
22
You need forecasts for 50,000 SKUs every week. Would you build one model per series or one global model?
One classical model per SKU is simple and interpretable but expensive to maintain, and it fails for short or sparse series. A global model, such as LightGBM trained on all SKUs with lags, calendar and product features, learns shared patterns and handles new items better. In practice I would use a global model as the main engine, keep statistical models for a few high-value series, and compare both in a rolling backtest.
23
What is U-Net and why is it popular for segmentation?
U-Net is an encoder-decoder network. The encoder downsamples to capture context, and the decoder upsamples back to full resolution to produce a per-pixel mask. Skip connections copy encoder feature maps to the matching decoder level, so fine spatial detail lost during downsampling is recovered. It works well with limited labelled data, which made it the standard for medical imaging and industrial defect segmentation, and it is also the backbone of many diffusion models.
24
Write Pandas code to compute each customer's average order value excluding the current order.
g = df.groupby('customer_id')['amount']
total = g.transform('sum')
count = g.transform('count')
# Leave-one-out mean; NaN when it is the customer's only order
df['avg_other_orders'] = (total - df['amount']) / (count - 1)
df.loc[count == 1, 'avg_other_orders'] = float('nan')
# For time-aware features, use only earlier orders instead
25
What is a sample ratio mismatch in an experiment and what do you do about it?
A sample ratio mismatch means the observed split between groups differs from the planned split, for example 52 to 48 instead of 50 to 50 with a large sample. A chi-square test on the counts confirms it. It usually signals a bug in assignment, redirects, bot filtering or logging, so the results cannot be trusted. Do not analyse the metric; find and fix the root cause and rerun the test.
26
What is SHAP and how does it explain model predictions?
SHAP assigns each feature a contribution to a single prediction based on Shapley values from game theory. The contributions add up to the difference between the prediction and the average prediction. It gives local explanations, like why one loan was rejected, and global views by aggregating values across rows. TreeSHAP is fast for tree models. Limits include slow computation for other models and misleading results when features are strongly correlated.
27
Write Python code to compare revenue per user between two groups using Welch's t-test.
import hashlib
def assign(user_id, experiment, variants=('control', 'treatment'), weights=(50, 50)):
key = f'{experiment}:{user_id}'.encode()
bucket = int(hashlib.sha256(key).hexdigest(), 16) % 100
cumulative = 0
for v, w in zip(variants, weights):
cumulative += w
if bucket < cumulative:
return v
# Same user + experiment always gets the same variant;
# salting with the experiment name keeps tests independent
29
Tell me about a time you had to deliver data under an urgent deadline.
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.
30
Why do ratio metrics like click-through rate per user need special variance calculation?
A metric like total clicks divided by total page views has a numerator and denominator that both vary by user, and page views within a user are correlated. Treating each page view as independent underestimates variance and inflates false positives. The delta method approximates the variance of a ratio of means using the variances and covariance of the per-user numerator and denominator. Bootstrap by user is an alternative when formulas get complicated.
31
A new checkout converts better on both mobile and desktop, but worse overall. How is that possible?
Simpson's paradox happens when a trend in several groups reverses when the groups are combined. Example: a new checkout converts better on both mobile and desktop, but worse overall, because most of its traffic came from mobile, which has lower conversion anyway. The mix of groups, not the treatment, drives the total. The lesson is to check segment-level results and confounding variables before drawing conclusions from aggregated numbers.
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
Parameter-efficient fine-tuning updates only a small number of parameters instead of the whole model. LoRA freezes the original weights and adds small low-rank matrices to selected layers, often attention projections, training under 1 percent of parameters. This cuts GPU memory and storage, and many task adapters can share one base model. QLoRA goes further by loading the base model in 4-bit precision. Quality is usually close to full fine-tuning.
34
How does a multi-armed bandit differ from a classic A/B test?
A classic A/B test splits traffic in fixed proportions until the end, then decides, which is best for learning and clean inference. A multi-armed bandit, such as Thompson sampling, shifts traffic towards better-performing variants as data arrives, reducing the cost of showing a weak variant. Bandits suit short-lived decisions like headlines or promotions. They make unbiased effect estimates and guardrail analysis harder, so they are poor for major product decisions.
35
For a warehouse, a stockout costs five times more than holding extra stock. How should the forecast change?
A forecast of the mean is the wrong target when costs are asymmetric. Forecast a quantile instead. The optimal quantile here is about 5 divided by 5 plus 1, roughly the 83rd percentile, which is the newsvendor critical ratio. Train with quantile or pinball loss, or use prediction intervals from a probabilistic model. Evaluate with pinball loss and the actual stockout and holding cost, not just MAE.
36
Your notebook runs on your laptop but fails on a colleague's machine. How do you make the work reproducible?
First pin the environment: a requirements.txt or conda environment file with exact versions, or a Docker image. Set random seeds for NumPy, scikit-learn and any framework you use. Remove hard-coded local paths and read them from a config file. Make sure data comes from a shared, versioned location. Finally, restart the kernel and run the notebook top to bottom, so hidden cell order bugs are caught before sharing.
37
Tree feature importance ranks an ID-like numeric column near the top. Why, and which importance method would you trust instead?
Impurity-based importance, the default in tree models, sums how much each feature reduces impurity across splits. It is fast but biased toward high-cardinality and continuous features, and it is computed on training data. Permutation importance shuffles one feature at a time on validation data and measures the drop in score, so it reflects real predictive value. Both can understate correlated features, because the model can lean on the copy.
38
Your product image classifier works on studio catalogue photos but fails on photos users take with their phones. Why, and what do you do?
This is domain shift: user photos have clutter, blur, poor lighting and odd angles that the model never saw. Collect and label a sample of real user photos and evaluate on them separately. Add augmentation for blur, noise, colour jitter, rotation and random crops, and fine-tune on a mix of studio and real images. Monitor accuracy on user photos in production, since that is the distribution that matters.
39
What is experiment tracking and why use a tool like MLflow?
Experiment tracking records each training run's parameters, code version, data version, metrics and output artefacts. Tools like MLflow or Weights and Biases store this in one place, so you can compare runs, reproduce the best model and see why something improved. Without it, results live in notebook outputs and memory. MLflow also offers a model registry to move approved models through staging and production.
40
What is CUPED and how does it reduce variance in experiments?
CUPED uses a pre-experiment covariate, usually the same metric for each user in the weeks before the test, to remove predictable variation. The adjusted metric is Y minus theta times (X minus the mean of X), where theta is cov(X, Y) divided by var(X). Because randomisation makes X balanced across groups, the estimate stays unbiased while variance can drop by 30 to 50 percent, letting tests reach significance faster with the same traffic.
Frequently asked questions
What is asked in Data Science interviews for 7 years of experience?
At seven years, interviews look for lead or staff level thinking. You should design data science roadmaps, platform choices and team processes, and explain how your work changed business metrics. Expect questions on building teams, setting evaluation standards, governance and responsible AI, and when to use GenAI versus classic ML across a portfolio of use cases.
How many questions should I practise before a Data Science interview?
Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.
Which topics matter most for 7 years of experience?
Focus first on Data science strategy, Platform and tooling choices, Team building, Responsible AI.