Data Science Interview Questions for 2 Years Experience
40 questions with answers for candidates with 2 years of experience — 5 easy, 33 medium, 2 hard.
What interviewers expect: 2 years experience
At two years, you should own a model or analysis end to end. Interviewers probe feature engineering, leakage, experiment design, model trade-offs and basic deployment awareness. Expect scenario questions like debugging a metric drop or a model that fails in production, and questions on how you worked with engineers and product managers.
This set is weighted towards Machine Learning (7), Deep Learning and NLP (6), Statistics and Probability (5), Computer Vision (4).
Feature engineering and leakage A/B testing Debugging scenarios Basic deployment
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
Write a Python function to split a long text into overlapping chunks by word count for a RAG index.
Type hints annotate expected types, for example def clean(df: pd.DataFrame, cols: list[str]) -> pd.DataFrame. Python does not enforce them at runtime, but tools like mypy and IDEs use them to catch mistakes early and give better autocomplete. In data teams they make shared pipeline code easier to read and review. They matter most in production code and libraries, less in quick exploratory notebooks.
04
What is mean Average Precision (mAP) in object detection?
For each class, detections are ranked by confidence and a precision-recall curve is computed, where a detection is a true positive if its IoU with an unmatched ground truth box passes a threshold. Average Precision is the area under that curve. mAP is the mean across classes. mAP@0.5 uses IoU 0.5, while mAP@0.5:0.95 averages over thresholds from 0.5 to 0.95 and rewards tighter boxes.
05
Your model API meets average latency but p99 latency is 900 ms against a 200 ms target. What do you do?
Profile slow requests to see if time goes to feature fetching, preprocessing, the model or the network. Common fixes: precompute and cache features, remove slow database calls from the request path, load the model once at start-up, use a faster runtime like ONNX, and warm up instances. Check garbage collection pauses, cold starts and autoscaling limits. Set timeouts with a safe fallback prediction for rare slow cases.
06
Write Python code to evaluate a forecasting model with expanding-window time series cross-validation.
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
from sklearn.metrics import mean_absolute_error
tscv = TimeSeriesSplit(n_splits=5, test_size=28)
scores = []
for tr, te in tscv.split(X):
model.fit(X.iloc[tr], y.iloc[tr])
pred = model.predict(X.iloc[te])
scores.append(mean_absolute_error(y.iloc[te], pred))
print(np.mean(scores), scores)
07
What is gradient descent and what does the learning rate do?
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
08
Write Python code to calculate the sample size per group needed to detect a lift from 5 percent to 5.5 percent conversion.
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.
10
How do you pull large data from a SQL database into Pandas efficiently?
Push as much work as possible into SQL: filter, aggregate and select only needed columns before pulling. Use pd.read_sql with a SQLAlchemy engine and chunksize to stream large results. For very large extracts, export to Parquet from the warehouse and read that, which is much faster than row-by-row transfer. Set dtypes like category early, and never use SELECT star on a big table from a notebook.
11
Tell me about a feature you engineered that significantly improved a model.
Situation: our delivery time model kept underestimating late-night orders. Task: reduce large errors. Action: I noticed restaurant prep time depended on how busy the kitchen was, so I built a feature for active orders at that restaurant in the last 30 minutes, computed point in time. Result: MAE dropped by 14 percent and late-night errors fell the most. It taught me to study the worst errors before adding generic features.
A learning curve plots training and validation scores against the size of the training set. If both scores are low and close, the model has high bias and needs more features or a more flexible model. If training is high but validation is much lower and the gap narrows as data grows, the model has high variance and more data will help. It tells you whether collecting more data is worth the cost.
14
Write Python code to compute a 95% bootstrap confidence interval for the mean.
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
17
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.
18
What are embeddings and vector databases, and why do LLM apps use them?
An embedding model turns text into a vector so that similar meanings are close in space. A vector database stores these vectors with metadata and finds the nearest ones to a query vector quickly using approximate nearest neighbour indexes like HNSW. LLM apps use them for semantic search and retrieval-augmented generation, finding the most relevant documents to put into the prompt. Examples include pgvector, FAISS and dedicated vector stores.
19
Tell me about a time your forecast was badly wrong. How did you handle it?
Situation: my weekly demand forecast under-predicted a category by 30 percent for a month. Task: explain the miss and stop it recurring. Action: I compared forecast and actuals by region and found a new distribution channel had launched that the model knew nothing about. I told the planning team quickly, added channel as a feature and set up a weekly error review. Result: error returned to normal and planners trusted the alerts.
20
Write PyTorch code to fine-tune a pretrained ResNet-18 for a 5-class problem by replacing its final layer.
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
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
22
What is subword tokenisation like BPE or WordPiece?
Subword tokenisers split text into frequent pieces between characters and full words. Byte Pair Encoding starts from characters and repeatedly merges the most frequent pairs. WordPiece, used by BERT, is similar but chooses merges by likelihood. Rare words like unhappiness become un, happi, ness, so there are no unknown words and the vocabulary stays around 30,000 to 100,000. Token counts also decide LLM cost and context use.
23
What is the difference between an epoch, a batch and an iteration?
Start with a pretrained sentence embedding model plus a simple classifier, or fine-tune a small transformer with class weights. For the rare categories, try few-shot approaches such as SetFit or an LLM with examples in the prompt, and generate or collect more examples. Merge categories that are rarely distinguishable. Report per-class F1 rather than overall accuracy, and route low-confidence predictions to a human queue.
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
26
Write SQL to show each customer's first order date, last order date and the gap between them in days.
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
Recursive feature elimination trains a model, ranks features by importance or coefficient size, removes the weakest ones, and repeats until the desired number remains. RFECV picks the number of features using cross-validation. It considers features together rather than one at a time. The downsides are high compute cost on large data and unstable results when features are correlated, so check stability across folds.
28
What do ACF and PACF plots tell you about a time series?
The ACF plot shows correlation between the series and its own lags, including indirect effects through intermediate lags. The PACF shows the correlation at each lag after removing the effect of shorter lags. For a stationary series, a PACF that cuts off after lag p suggests an AR(p) term, and an ACF that cuts off after lag q suggests an MA(q) term. Spikes at lag 7 or 12 reveal weekly or yearly seasonality.
29
What is the difference between a subquery and a correlated subquery?
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.
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
31
Why do residual connections make very deep networks easier to train?
A residual block adds its input to its output, so the layers learn a residual F(x) and the block outputs F(x) plus x. If extra layers are not useful, they can learn to output near zero and the block behaves like identity. The skip path also lets gradients flow directly to early layers, reducing vanishing gradients. This is why ResNets with 50 or 100-plus layers train well where plain deep networks degrade.
32
What is the difference between a one-tailed and a two-tailed test?
A two-tailed test checks for a difference in either direction, for example whether a new page changes conversion up or down. A one-tailed test checks only one direction, such as whether it increases conversion. One-tailed tests have more power for that direction but ignore harm in the other direction. In most product experiments a two-tailed test is the safer default unless the direction was fixed before seeing data.
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.
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.
35
Tell me about a computer vision project where data quality was the biggest challenge.
Situation: a shelf-detection model plateaued at low accuracy. Task: find out why and fix it. Action: I reviewed 500 errors and found that a third were labelling mistakes, with inconsistent boxes for partly hidden products. I rewrote the guidelines with visual examples, had a second annotator review hard images and relabelled the worst batch. Result: mAP rose by 9 points without changing the model, and labelling rework dropped sharply.
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.
37
How does linear regression work and what are its assumptions?
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
38
What is SARIMA and how does it extend a plain ARIMA model?
SARIMA adds seasonal terms to ARIMA. It is written ARIMA(p,d,q)(P,D,Q)m, where the second set are seasonal AR, differencing and MA orders, and m is the season length, such as 7 for daily data with a weekly cycle or 12 for monthly data. SARIMAX further allows external regressors like price or holidays. It handles one seasonal period well but struggles with multiple seasonalities, such as daily plus yearly.
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
Frequently asked questions
What is asked in Data Science interviews for 2 years of experience?
At two years, you should own a model or analysis end to end. Interviewers probe feature engineering, leakage, experiment design, model trade-offs and basic deployment awareness. Expect scenario questions like debugging a metric drop or a model that fails in production, and questions on how you worked with engineers and product managers.
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 2 years of experience?
Focus first on Feature engineering and leakage, A/B testing, Debugging scenarios, Basic deployment.