Skip to content

Data Science Interview Questions for 5 Years Experience

40 questions with answers for candidates with 5 years of experience — 1 easy, 22 medium, 17 hard.

What interviewers expect: 5 years experience

At five years, you are judged as a senior who can frame problems, choose the right approach and guide others. Expect ML system design, causal inference, trade-offs between accuracy, latency, cost and explainability, and deep project discussions. Behavioural rounds focus on mentoring, prioritisation, influencing decisions and handling failures in production.

This set is weighted towards Generative AI and LLMs (5), Statistics and Probability (5), Deep Learning and NLP (4), SQL for Data Science (4).

ML system design Causal inference Mentoring and leadership Business impact
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 you turn text columns into features for a tabular model?

Save to ▾
Show answer
Simple options are length, word count and keyword flags. TF-IDF vectors capture important words and work well with linear models. For meaning, use sentence embeddings from a pretrained model and optionally reduce them with PCA. You can also train a separate text classifier and feed its predicted score as one feature. Fit any vocabulary or encoder on training data only to avoid leakage.
02

Your neural network's training loss suddenly becomes NaN. What do you check?

Save to ▾
Show answer
Common causes are a learning rate that is too high, exploding gradients, bad input values, and unstable maths like log of zero. I would check the input data for NaN or infinite values, lower the learning rate, add gradient clipping, and make sure the loss uses the stable built-in version with logits. With mixed precision, I would check the loss scaler. Logging gradient norms per step helps find the exact point it breaks.
03

Your LLM assistant confidently quotes a policy clause that does not exist. Why does this happen and how do you reduce it?

Save to ▾
Show answer
Hallucination is when a model produces confident text that is false or not supported by any source. It happens because the model generates plausible tokens rather than checking facts. Reduce it by grounding answers in retrieved documents, asking the model to cite sources and say I do not know when context is missing, using low temperature, and validating outputs with rules or a second checking step. Measure it with a labelled evaluation set.
04

Your daily sales forecast badly misses the Diwali spike every year. How do you fix it?

Save to ▾
Show answer
The model is treating Diwali as noise because the festival moves on the calendar and a fixed yearly seasonality does not align. Add explicit holiday features: a flag for Diwali and a few days before and after, since buying starts early. Include other regional festivals and sale events too. Models like Prophet or gradient boosting with holiday features handle this well. Then backtest specifically on past festive periods to confirm the fix.
05

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.
06

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
07

Tell me about a time you decided an LLM was not the right solution for a problem.

Save to ▾
Show answer
Situation: a team wanted an LLM to categorise transactions into 12 fixed categories. Task: recommend an approach. Action: I benchmarked an LLM against a gradient boosting model on labelled history, comparing accuracy, latency and cost per million records. The classic model matched accuracy at a fraction of the cost and ran in milliseconds. Result: we shipped it and used the LLM only for the few low-confidence cases.
08

Write SQL to find users who logged in on at least three consecutive days.

Save to ▾
Show answer
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)
09

Tell me about a time you had to build a model when the requirements were unclear.

Save to ▾
Show answer
Situation: a sales head asked for a model to find good leads but could not define good. Task: turn this into a clear target. Action: I met the team, looked at past deals, and proposed converted within 60 days as the label, with expected revenue as a secondary view. I shared a quick baseline in a week to get feedback. Result: the definition was agreed, and the final model raised conversion in the top decile.
10

Tell me about a time you deployed a model under a tight deadline.

Save to ▾
Show answer
Situation: a pricing model had to go live before a sale in ten days. Task: deploy safely in that window. Action: I cut scope to batch scoring instead of real-time, reused our standard Docker and Airflow template, wrote tests for the key features and set up a dashboard for score distribution. Result: it went live two days early and ran without incidents during the sale. Real-time scoring followed a month later.
11

What are guardrails in LLM applications?

Save to ▾
Show answer
Guardrails are checks around the model that keep inputs and outputs safe and on-topic. Input guardrails detect prompt injection, abuse or off-topic requests. Output guardrails check for personal data, toxic content, policy violations or invalid formats before the answer reaches the user. They can be rules, classifiers or a second LLM call. Good guardrails also define fallback responses and log blocked cases for review.
12

Tell me about a time you stopped a team from shipping a change based on a flawed experiment.

Save to ▾
Show answer
Situation: a team wanted to launch a feature after a test showed a 6 percent lift. Task: as the reviewing data scientist, validate it. Action: I found that assignment was triggered after users clicked into the feature, so treatment had only engaged users. I explained the selection bias simply, proposed assigning at app open, and helped rerun it. Result: the true lift was under 1 percent, and we added assignment checks to the review template.
13

A feature was launched to all users with no control group. How would you estimate its causal impact?

Save to ▾
Show answer
Without randomisation I would use quasi-experimental methods. Difference-in-differences compares the change in a group that got the feature early with one that did not, if rollout was staggered. Interrupted time series or synthetic control builds a counterfactual from pre-launch trends or similar markets. Regression discontinuity works if eligibility had a cut-off. I would state the assumptions clearly and check them with placebo tests.
14

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.
15

Write PyTorch code to fine-tune a pretrained ResNet-18 for a 5-class problem by replacing its final layer.

Save to ▾
Show answer
import torch, torch.nn as nn from torchvision import models model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT) for p in model.parameters(): p.requires_grad = False # freeze backbone model.fc = nn.Linear(model.fc.in_features, 5) opt = torch.optim.AdamW(model.fc.parameters(), lr=1e-3) loss_fn = nn.CrossEntropyLoss() # train head first, then unfreeze later layers with a lower lr
16

Your product image classifier works on studio catalogue photos but fails on photos users take with their phones. Why, and what do you do?

Save to ▾
Show answer
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.
17

What are anchor boxes, and why have anchor-free detectors become popular?

Save to ▾
Show answer
Anchor boxes are predefined boxes of several sizes and aspect ratios placed at each grid location; the detector predicts offsets from them and a class score. They need careful tuning to match object shapes in your data and create many redundant predictions. Anchor-free detectors, such as FCOS-style or centre-point methods, predict object centres and box sizes directly. They have fewer hyperparameters, generalise better to unusual shapes and simplify the pipeline.
18

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.
19

Write Python code to apply a CUPED adjustment using each user's pre-experiment metric.

Save to ▾
Show answer
import numpy as np # df has: variant, y (metric during test), x (same metric pre-test) x, y = df['x'].to_numpy(), df['y'].to_numpy() theta = np.cov(x, y, ddof=1)[0, 1] / np.var(x, ddof=1) df['y_cuped'] = y - theta * (x - x.mean()) print(df.groupby('variant')[['y', 'y_cuped']].agg(['mean', 'var'])) # Means stay comparable; variance of y_cuped is lower
20

How does a Vision Transformer differ from a CNN?

Save to ▾
Show answer
A Vision Transformer splits an image into fixed patches, such as 16x16, flattens each into a token embedding, adds position embeddings and processes them with self-attention. Every patch can attend to every other patch from the first layer, giving global context. CNNs have built-in locality and translation biases, so they learn well from smaller datasets. ViTs need more data or strong pretraining but scale very well and are now common backbones.
21

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.
22

How do you profile and speed up slow Python code?

Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
23

Write SQL to find the top 3 products by revenue in each category.

Save to ▾
Show answer
WITH rev AS ( SELECT category, product_id, SUM(price * qty) AS revenue FROM order_items GROUP BY category, product_id ), ranked AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS rn FROM rev ) SELECT category, product_id, revenue FROM ranked WHERE rn <= 3;
24

What is the difference between probability and likelihood?

Save to ▾
Show answer
Probability fixes the parameters and asks how likely different data are, for example the chance of 7 heads in 10 tosses if the coin is fair. Likelihood fixes the observed data and asks how plausible different parameter values are, for example which coin bias best explains 7 heads. The likelihood function is not a probability distribution over parameters. Maximum likelihood estimation picks the parameter value that maximises it.
25

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
26

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.
27

Write SQL to show each customer's first order date, last order date and the gap between them in days.

Save to ▾
Show answer
SELECT customer_id, MIN(order_date) AS first_order, MAX(order_date) AS last_order, MAX(order_date) - MIN(order_date) AS days_between, COUNT(*) AS orders FROM orders GROUP BY customer_id ORDER BY days_between DESC; -- PostgreSQL: DATE minus DATE gives days; use DATEDIFF in other engines
28

A feature works well offline but is not available at prediction time in production. How do you handle this?

Save to ▾
Show answer
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.
29

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
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.
30

What is a sample ratio mismatch in an experiment and what do you do about it?

Save to ▾
Show answer
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.
31

How does Kubernetes help in serving machine learning models?

Save to ▾
Show answer
Kubernetes runs containerised model services across a cluster. It restarts failed containers, scales the number of replicas based on traffic or CPU, rolls out new versions gradually and can roll back, and schedules GPU workloads on the right nodes. Tools built on it, like KServe or Seldon, add model-specific features such as canary releases and autoscaling to zero. The trade-off is operational complexity, so small teams often use managed services.
32

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.
33

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.
34

Your A/B test shows a significant lift after 2 days. The product team wants to ship now. What do you say?

Save to ▾
Show answer
I would ask them to wait for the planned duration. Checking early and stopping on the first significant result, called peeking, inflates false positives. Two days also misses weekly patterns and novelty effects, where users click a new feature just because it is new. If speed matters, we can use a sequential testing method designed for early stopping. Otherwise we run the full sample size calculated before launch.
35

Explain logistic regression.

Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
36

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
37

When would you use prompting, RAG or fine-tuning?

Save to ▾
Show answer
Start with prompting; it is cheapest and fastest to iterate. Use RAG when the model needs private or frequently changing knowledge, like policy documents, because you can update the index without retraining and cite sources. Use fine-tuning to change behaviour, style or output format consistently, or to make a smaller model handle a narrow task cheaply. Fine-tuning is a poor way to add facts. Many systems combine RAG with a lightly tuned model.
38

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
39

Write a Dockerfile for a Python model API.

Save to ▾
Show answer
FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY app/ ./app COPY model.joblib . EXPOSE 8000 CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
40

A feature won its A/B test with a 4 percent lift, but after full launch the metric barely moved. Why might that happen?

Save to ▾
Show answer
Several reasons are common. Winner's curse: significant results from underpowered tests tend to overestimate the true effect. Novelty effect faded after launch. Seasonality or other launches changed the baseline, so a before-after comparison is misleading. The test population may differ from all users, for example only one platform. Use a holdout after launch to measure real impact, and run tests with adequate power and duration.

Frequently asked questions

What is asked in Data Science interviews for 5 years of experience?

At five years, you are judged as a senior who can frame problems, choose the right approach and guide others. Expect ML system design, causal inference, trade-offs between accuracy, latency, cost and explainability, and deep project discussions. Behavioural rounds focus on mentoring, prioritisation, influencing decisions and handling failures in production.

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 5 years of experience?

Focus first on ML system design, Causal inference, Mentoring and leadership, Business impact.