Data science interview questions today test five things: statistics, machine learning, Python, SQL coding, and how you reason through a business problem. Most companies now add a sixth area: how you work with large language models (LLMs) and AI tools. This guide covers 70 data scientist interview questions and answers across all six areas, so freshers and experienced candidates can practice the full range in one place.
The questions follow the order in which most interviews unfold. You start with the basics that screening rounds use, move to the statistics and machine learning that technical rounds probe, and then work through Python and coding problems with full solutions. After that comes GenAI, case study, and behavioral questions, followed by data science MCQs and a four-week data scientist interview preparation plan.
Each answer is written the way you would say it in the room: a direct definition first, then an example or the trade-off an interviewer expects you to mention. Where a question is commonly asked in a different form, the alternate phrasing is noted so you can recognize it.

How a Data Scientist Interview Is Structured
Most data scientist interviews run four to five rounds, and each round tests a different skill. Knowing what each round looks for tells you which of the questions below to prioritize.
Round | What it tests | Typical format |
|---|---|---|
Recruiter or HR screen | Role fit, motivation, salary expectations, notice period | 20–30 minute call |
Online assessment | Data science MCQs, basic Python and SQL | Timed test on a platform such as HackerRank |
Technical interview | Statistics, machine learning concepts, model evaluation | 45–60 minute discussion |
Coding interview | SQL queries, Python and pandas problems | Live coding or shared notebook |
Case study or take-home | Problem framing, metric choice, end-to-end modeling | Business scenario or 2–5 day assignment |
Hiring manager and behavioral | Communication, stakeholder handling, past projects | 30–45 minute conversation |

Start-ups often merge the technical and coding rounds into one, while large product companies tend to keep them separate and add a dedicated product-sense round. Whichever pattern you face, the technical and coding rounds carry the most weight, which is why most questions in this guide focus on them.
Basic Data Science Interview Questions for Freshers
Screening rounds open with these questions because they show whether your foundation is solid. Interviewers also use them to judge how clearly you explain ideas, so keep each answer short and structured.
1. What is data science, and how is it different from data analytics?
Data science is the field that uses statistics, programming, and machine learning to extract insights from data and build models that predict outcomes. Data analytics overlaps with it but focuses mainly on describing what has already happened through reporting, dashboards, and diagnostic analysis.
The simplest way to frame the difference is by the question each one answers. Analytics asks "what happened and why?", while data science also asks "what will happen next, and what should we do about it?" That forward-looking element is why data scientists spend more time on modeling, experimentation, and deployment.
Also read: Data Science vs. Data Analytics: Which One to Choose?
2. Walk me through the stages of a data science project.
A typical project moves through six stages, often described by the CRISP-DM framework:
Business understanding: Define the problem, the decision it supports, and the metric that measures success.
Data understanding: Identify sources, check quality, and run exploratory data analysis (EDA).
Data preparation: Clean, join, and transform the data, and engineer features.
Modeling: Train candidate models and tune their hyperparameters.
Evaluation: Test models on held-out data against the business metric, not only accuracy.
Deployment and monitoring: Put the model into production and track its performance over time.
Interviewers like to hear that the stages loop back. For example, poor evaluation results often send you back to data preparation rather than forward to deployment.
3. What is the difference between supervised and unsupervised learning?
Supervised learning trains a model on labeled data, where each input has a known output. Common examples include linear regression, logistic regression, decision trees, and support vector machines, and they are used for prediction tasks such as forecasting sales or classifying emails.

Unsupervised learning works on unlabeled data and finds structure on its own. Common examples include clustering (such as k-means), dimensionality reduction (such as PCA), and anomaly detection, and they are used to segment customers or flag unusual transactions.
It also helps to mention self-supervised learning, because it now underpins large language models. Here, the model creates its own labels from raw data, for instance by predicting the next word in a sentence.
Also read: Supervised vs. Unsupervised Learning in Machine Learning
4. What is the difference between structured and unstructured data?
Structured data fits neatly into rows and columns with a fixed schema, such as sales tables in a SQL database. Unstructured data has no predefined format, so it includes text, images, audio, and video.
The distinction matters because each type needs different tools. Structured data is handled with SQL and pandas, whereas unstructured data typically needs natural language processing, computer vision, or, increasingly, embeddings and LLMs to convert it into a usable form.
5. What are univariate, bivariate and multivariate analyses?
Univariate analysis examines one variable at a time, using measures such as the mean, median, mode, range and standard deviation. The height distribution of a population is a typical example.
Bivariate analysis studies the relationship between two variables, such as airline ticket sales against the day of the week. Scatter plots, correlation coefficients, and cross-tabulations are the standard tools.
Multivariate analysis extends this to three or more variables at once. Estimating the likelihood of a disease from age, existing conditions, and lifestyle habits together is a multivariate problem, usually tackled with regression or other models.
6. What is feature engineering, and why does it matter?
Feature engineering is the process of creating, transforming, or selecting input variables so that a model can learn patterns more easily. Examples include extracting the day of the week from a timestamp, calculating a customer's average order value, or encoding categories as numbers.
It matters because a model can only learn from the signals it is given. On tabular data, well-designed features often improve performance more than switching to a more complex algorithm.
7. How do you handle missing values?
Start by asking why the values are missing, because the pattern itself can be informative. Data can be missing completely at random, missing at random (linked to other observed variables), or missing not at random (linked to the missing value itself).
Once you understand the pattern, choose a treatment:
Deletion: Drop rows or columns when very little data is missing and the loss will not bias the sample.
Simple imputation: Fill numeric gaps with the mean or median, and categorical gaps with the mode or an "Unknown" label.
Model-based imputation: Use methods such as KNN imputation or iterative imputation when variables are strongly related.
Indicator flags: Add a column marking which values were missing, so the model can learn from the missingness itself.
Always fit any imputation on the training data only, and then apply it to the test data. Otherwise, information from the test set leaks into training.
8. How do you detect and treat outliers?
Outliers are usually detected with the interquartile range (IQR) rule, z-scores, or visual checks such as box plots. The IQR rule flags any value below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR.
Treatment depends on whether the outlier is an error or a genuine extreme. Correct or remove data-entry errors, cap genuine extremes at the 1st and 99th percentiles, transform with a log scale, or use robust models such as tree-based methods. In fraud detection, the outliers may be exactly what you are looking for, so removing them would defeat the purpose.
9. What are overfitting and underfitting?
Overfitting happens when a model learns the noise in the training data along with the real pattern. It performs very well on training data but poorly on new data, which is like memorizing answers instead of understanding the subject.
Underfitting is the opposite problem: the model is too simple to capture the pattern. Fitting a straight line to clearly curved data is a classic example, and it performs poorly on both training and test data.

To reduce overfitting, you can gather more data, simplify the model, apply regularization, use cross-validation, or stop training early. To fix underfitting, you add relevant features, use a more flexible model, or reduce regularization.
Image suggestion (reuse): Blog-Image-7.jpg from the original post, which shows underfit, balanced and overfit curves. Alt text: "Underfitting vs overfitting in machine learning".
10. What is the bias–variance trade-off?
Bias is the error that comes from oversimplifying the problem, and high bias leads to underfitting. Variance is the error that comes from being too sensitive to the training data, and high variance leads to overfitting.
The two pull against each other. Making a model more complex usually lowers bias but raises variance, so the goal is the level of complexity that minimizes total error on unseen data. Linear and logistic regression tend to be high-bias models, while deep decision trees and k-NN with a small k tend to be high-variance models.

For more detail: What Is Regularization in Machine Learning? Techniques & Methods
11. What is cross-validation, and why is it used?
Cross-validation estimates how well a model will perform on unseen data by training and testing it on different splits of the dataset. In k-fold cross-validation, the data is split into k parts, and the model is trained k times, each time holding out a different part for testing.
Averaging the k scores gives a more reliable estimate than a single train-test split. For time-series data, you should use time-based splits instead, because shuffling would let the model learn from the future.
12. What is data leakage, and how do you prevent it?
Data leakage occurs when information that wouldn't be available at prediction time sneaks into training. The model then looks excellent in testing but fails in production.
A common example is scaling or imputing the full dataset before splitting it, which lets test-set statistics influence training. Another is including a feature that is recorded only after the outcome, such as a "refund issued" flag in a model predicting complaints. Prevent leakage by splitting the data first, fitting all preprocessing inside a pipeline on training data only, and checking each feature's timestamp against the prediction moment.
Statistics and Probability Interview Questions in Data Science
Statistics questions appear in almost every technical round because they reveal whether you understand why a model works, not just how to call it. If you are new to these ideas, Fundamentals of Statistics for Data Science is a useful primer before you practice the questions below.
13. What is a normal distribution?
A normal distribution is a symmetric, bell-shaped distribution in which most values cluster around the center and become rarer as they move away in either direction. Its mean, median, and mode are equal, and two parameters fully describe it: the mean and the standard deviation.
It follows the empirical rule, so about 68% of values lie within one standard deviation of the mean, 95% within two, and 99.7% within three. Many statistical tests assume normality, so checking it is a routine step in analysis.

14. What is the Central Limit Theorem, and why is it important?
The Central Limit Theorem (CLT) states that the distribution of sample means approaches a normal distribution as the sample size grows, even if the underlying population is not normal. The usual rule of thumb is a sample size of 30 or more.
The CLT matters because it lets us use normal-based methods, such as confidence intervals and z-tests, on data that is not itself normally distributed. A/B tests on skewed metrics like revenue per user rely on it.
Related: Application of Central Limit Theorem in Supply Chain: An Illustration
15. What is a p-value?
A p-value is the probability of seeing results at least as extreme as the ones observed, assuming the null hypothesis is true. A small p-value means the observed data would be unlikely if the null hypothesis held.
If the p-value is below the chosen significance level (often 0.05), you reject the null hypothesis. If it is above, you fail to reject it, which is not the same as proving the null is true. Interviewers also look for the common misreading: a p-value is not the probability that the null hypothesis is true.
16. What are Type I and Type II errors?
A Type I error (false positive) occurs when you reject a null hypothesis that is actually true. Its probability is the significance level, alpha.
A Type II error (false negative) occurs when you fail to reject a null hypothesis that is actually false. Its probability is beta, and 1 − beta is the test's statistical power. Lowering alpha reduces Type I errors but raises Type II errors for the same sample size, so the only way to reduce both is to collect more data.

17. What is a confidence interval?
A confidence interval gives a range of plausible values for a population parameter, based on sample data. A 95% confidence interval means that if you repeated the sampling many times, about 95% of the intervals built this way would contain the true value.
It does not mean there is a 95% probability that the true value lies in this particular interval. That distinction is a favorite follow-up question.
18. What is the difference between correlation and covariance?
Both measure how two variables move together, but they differ in scale. Covariance shows the direction of the relationship, but its value depends on the variables' units, so it is hard to compare across datasets.
Correlation standardizes covariance by dividing it by the product of the two standard deviations. The result always lies between −1 and +1, which makes the strength of the relationship easy to compare. Neither measure proves causation, and both capture only linear relationships.
19. What is A/B testing, and how would you design one?
A/B testing is a randomized controlled experiment that compares two versions of something, such as a control and a variant of a checkout page, to see which performs better on a chosen metric.
A sound design follows these steps:
Define the hypothesis and a primary metric, such as conversion rate.
Choose guardrail metrics that must not get worse, such as page load time or refund rate.
Calculate the sample size from the minimum detectable effect, significance level and desired power.
Randomize users into groups and run the test for full weekly cycles to avoid day-of-week bias.
Analyze the result with the planned test, and avoid stopping early just because the result looks significant.

Peeking at results repeatedly and stopping as soon as p falls below 0.05 inflates the false-positive rate, so mentioning this shows real experience.
20. What is the law of large numbers?
The law of large numbers states that as the number of trials or the sample size increases, the sample mean gets closer to the population mean. Tossing a fair coin 10 times might give 70% heads, but tossing it 10,000 times will give a share very close to 50%.
This is related to the CLT but answers a different question. The law of large numbers says the sample mean converges to the true mean, while the CLT describes the shape of the distribution of sample means.
21. When would you use the median instead of the mean?
Use the median when the data is skewed or contains outliers, because the mean is pulled toward extreme values while the median is not. Household income is a common example, since a few very high earners can pull the mean well above what a typical household earns.
The median is also the better summary for ordinal data, such as survey ratings from 1 to 5, where the distance between categories is not truly numeric.
22. What types of sampling bias can affect an analysis?
Sampling bias occurs when the sample does not represent the population, which makes any conclusion drawn from it unreliable. The common types are:
Selection bias: The method of choosing participants favors some groups over others.
Undercoverage bias: Some parts of the population are not adequately represented, such as an online survey that misses people without internet access.
Survivorship bias: Only the subjects that passed a selection process are analyzed, such as studying only successful start-ups to find the secrets of success.
Non-response bias: People who choose not to respond differ systematically from those who do.
Attrition bias: Participants drop out of a study unevenly, which is a serious problem in clinical trials.
23. What is Bayes' theorem, and why is Naive Bayes called "naive"?
Bayes' theorem updates an event's probability based on new evidence. It states that P(A|B) = P(B|A) × P(A) / P(B), so it revises a prior belief in light of observed data.
The Naive Bayes classifier applies this theorem but assumes all features are independent given the class. That assumption is rarely true in practice, which is why it is called naive. Even so, the model works surprisingly well for text tasks such as spam filtering, because it is fast and needs little training data.
Machine Learning and Data Science Technical Interview Questions
Once the basics are clear, data science technical interview questions move to algorithms and model evaluation. Here, interviewers expect you to explain how a model works, when you would choose it, and how you would judge whether it is good enough.
24. What is linear regression, and what are its assumptions?
Linear regression is a supervised learning algorithm that models a continuous target variable as a linear combination of one or more input variables. With one input variable, it is called simple linear regression, and with two or more, it is called multiple linear regression.

The model relies on five key assumptions:
Linearity: The relationship between the inputs and the target is linear.
Independence: Observations are independent of each other.
Homoscedasticity: The residuals have constant variance across all levels of the inputs.
Normality of residuals: The residuals are approximately normally distributed.
No multicollinearity: The input variables are not highly correlated.
Violating these assumptions does not always ruin predictions, but it makes coefficients and p-values unreliable for interpretation.
25. Explain logistic regression in simple terms.
Logistic regression predicts the probability of a binary outcome, such as whether a customer will churn. It takes a linear combination of the input variables and passes it through a sigmoid function, which squeezes the result into a probability between 0 and 1.
A threshold, often 0.5, then converts that probability into a class. For example, a model predicting whether a player will win a match might use training hours and fitness scores as inputs, and output a 0.72 probability of winning. Despite its name, logistic regression is a classification algorithm, not a regression one.
26. How does a decision tree work?
A decision tree splits the data into smaller and smaller groups using simple if-then rules on the features. Each internal node tests a feature, each branch represents an outcome of that test, and each leaf holds a prediction.

The algorithm chooses each split to make the resulting groups as pure as possible, using measures such as Gini impurity or entropy for classification and variance reduction for regression. CART and ID3 are the best-known algorithms. Decision trees are easy to interpret, but a single deep tree overfits easily, so they are usually pruned or combined into ensembles.
27. What is a random forest, and why does it usually beat a single decision tree?
A random forest is an ensemble of many decision trees, each trained on a random bootstrap sample of the data and a random subset of features at each split. For classification, the forest takes a majority vote across trees, and for regression, it averages their predictions.
The randomness makes the trees different from one another, so their individual errors partly cancel out. As a result, a random forest has much lower variance than one deep tree while keeping low bias. It also provides feature importance scores and an out-of-bag error estimate, although cross-validation is still good practice when comparing models.

This question is sometimes asked as "Would you prefer 50 small decision trees or one large tree?" The answer is usually the ensemble, for the reasons above.
28. How is gradient boosting different from a random forest?
Both are tree ensembles, but they build trees differently. A random forest builds trees independently and in parallel, then combines them, which mainly reduces variance.
Gradient boosting builds trees sequentially, with each new tree trained to correct the errors of the previous trees, which mainly reduces bias. Libraries such as XGBoost, LightGBM, and CatBoost implement this approach and often deliver the best results on tabular data. The trade-off is that boosting needs more careful tuning of the learning rate and tree depth to avoid overfitting.
29. Explain the support vector machine (SVM) algorithm.
A support vector machine finds the boundary, called a hyperplane, that separates classes with the widest possible margin. The data points closest to that boundary are the support vectors, and they alone determine the boundary's position.
When the classes cannot be separated by a straight line, SVM uses the kernel trick, with kernels such as the radial basis function (RBF), to map data into a higher-dimensional space where a separating hyperplane exists. SVMs work well on medium-sized datasets with many features, but they scale poorly to very large datasets.
For more details: Introduction To SVM – Support Vector Machine Algorithm in Machine Learning
30. What is the difference between L1 and L2 regularization?
Regularization adds a penalty for model complexity to the loss function, which discourages overfitting. The two common types differ in how they penalize the coefficients.
L1 regularization (Lasso) adds the sum of the absolute values of the coefficients. It can shrink some coefficients to exactly zero, so it also performs feature selection. L2 regularization (Ridge) adds the sum of the squared coefficients, which shrinks all coefficients toward zero without eliminating any. Elastic Net combines both penalties and is useful when features are correlated.
31. What is a confusion matrix, and which metrics come from it?
A confusion matrix is a table that compares a classifier's predictions with the actual labels. For a binary classifier, it has four cells:
True Positive (TP): The model predicted positive, and the case was positive.
False Positive (FP): The model predicted positive, but the case was negative.
True Negative (TN): The model predicted negative, and the case was negative.
False Negative (FN): The model predicted negative, but the case was positive.

The key evaluation metrics are calculated from these cells. Accuracy is (TP + TN) / total, precision is TP / (TP + FP), recall (also called sensitivity) is TP / (TP + FN), and specificity is TN / (TN + FP). The F1 score is the harmonic mean of precision and recall, which is useful when you need to balance the two.
32. Why is accuracy misleading on imbalanced data, and what would you use instead?
Accuracy is misleading when one class dominates. If only 1% of transactions are fraudulent, a model that predicts "not fraud" every time is 99% accurate yet catches no fraud at all.
For imbalanced data, it is better to report precision, recall, the F1 score, and the precision-recall AUC, because they focus on the minority class. ROC-AUC is still useful for comparing models, but it can look optimistic when negatives vastly outnumber positives. To improve the model itself, you can use class weights, resampling techniques such as SMOTE, or adjust the decision threshold.
33. Would you rather minimize false positives or false negatives?
The answer depends on the cost of each error, so a strong response always ties it to a scenario. In cancer screening, a false negative means a sick patient goes untreated, so you minimize false negatives and accept more false positives that further tests can rule out.
In a spam filter, the priority reverses. A false positive sends an important email to the spam folder, which is costlier than letting an occasional spam message through. In loan approval, both errors matter: false positives approve risky borrowers, and false negatives turn away good customers, so the threshold depends on the cost of each.
34. How does k-means clustering work, and how do you choose k?
K-means groups data into k clusters by repeating two steps. It assigns each point to the nearest cluster center, and then moves each center to the mean of its assigned points, until the assignments stop changing.
To choose k, you can use the elbow method, which plots within-cluster variance against k and looks for the point where gains level off. The silhouette score is another option, as it measures how well each point fits its own cluster compared with the next nearest one. Business context should also guide the choice, since five usable customer segments may be more valuable than nine statistically neat ones.
35. What is PCA, and when would you use it?
Principal Component Analysis (PCA) is a dimensionality reduction technique that transforms correlated features into a smaller set of uncorrelated components. The first component captures the most variance in the data, the second captures the most remaining variance, and so on.
PCA is useful when you have many correlated features, need to speed up training or want to visualize high-dimensional data in two dimensions. The trade-off is interpretability, because each component blends the original features. Remember to standardize the features first, since PCA is sensitive to scale.
36. What are recommender systems, and what types exist?
Recommender systems predict which items a user is likely to want, based on behavior and item properties. They fall into three main types:
Collaborative filtering: Recommendations are based on the behavior of similar users, as in an online store's "customers who bought this also bought" section.
Content-based filtering: Recommendations are based on the attributes of items a user already liked, such as suggesting songs of the same genre or artist.
Hybrid systems: Combine both approaches to offset their weaknesses, such as the cold-start problem for new users.
Modern platforms also use embeddings and deep learning to represent users and items. This question is sometimes framed as "What type of recommender system do you think Netflix or Spotify uses?", and the honest answer is a hybrid.
37. How often should you retrain a model?
There is no fixed schedule, because retraining should be driven by evidence, not habit. A model needs retraining when its performance drops, which usually happens because the data or the relationships in it have changed.
This change is called drift, and it comes in two forms. Data drift is a shift in the input distribution, such as a new customer segment, while concept drift is a change in the relationship between inputs and outcome, such as fraud patterns evolving. Monitoring both, along with the live business metric, tells you when to retrain. Some teams also retrain on a regular schedule as a safeguard.
38. You have 4 GB of RAM but need to train a model on a 10 GB dataset. What would you do?
First, ask which model you need to train, because the answer changes the approach. Interviewers often want to see that you clarify before solving.
After that, you have several options. You can load and process the data in chunks with pandas, use libraries built for out-of-core processing such as Dask or Polars, or train models that support incremental learning, such as scikit-learn's SGDClassifier with partial_fit(). You can train neural networks in mini-batches that stream from disk. You can also reduce memory by downcasting data types, dropping unused columns, sampling the data, or moving the job to a cloud machine with more memory.
You may also like to read: How to Choose The Best Algorithm for Your Applied AI & ML Solution and Top 45 Machine Learning Interview Questions and Answers
Data Science Python Interview Questions
Python is the default language for data science, so data science Python interview questions appear in nearly every process. They test whether you know the core language, the main libraries, and the habits that keep data code fast and correct. For a deeper set, see Top 50 Python Interview Questions for Data Science.
39. Which Python libraries do you use for data science, and what is each for?
A typical data science stack covers data handling, modeling, and visualization:
NumPy: It provides fast multi-dimensional arrays and numerical operations.
pandas: It handles tabular data through DataFrames for cleaning, joining, and aggregation.
Polars: A newer, faster DataFrame library useful for large datasets.
SciPy: It builds on NumPy with scientific functions for statistics, optimization, and integration.
scikit-learn: It offers classical machine learning models, preprocessing, and evaluation tools.
XGBoost and LightGBM: They implement gradient boosting for tabular data.
PyTorch and TensorFlow: Used for deep learning.
Matplotlib, Seaborn, and Plotly: They create static and interactive charts.
Interviewers usually follow up by asking which library you would choose for a specific task, so be ready to justify your picks.
You may also like to read: 50 Ultimate Python Data Science Libraries to Learn
40. What is the difference between a list and a tuple?
Both lists and tuples are ordered sequences that can hold items of any type. The key difference is that lists are mutable, so you can add, remove, or change items, while tuples are immutable once created.
That immutability has practical uses. Tuples are slightly faster and use less memory, and because they are hashable (when their contents are), you can use them as dictionary keys. A good rule of thumb is to use a list for a collection that will change and a tuple for a fixed record, such as a pair of coordinates.
Also read: List vs. Tuple: Understanding the Key Differences
41. Why use NumPy arrays instead of Python lists?
NumPy arrays store elements of one data type in a contiguous block of memory, which makes them far faster and more compact than lists for numerical work. They also support vectorized operations, so you can add two arrays element by element without writing a loop.
For example, np.array([1, 2, 3]) * 2 returns [2, 4, 6], whereas the same operation on a list repeats it to give [1, 2, 3, 1, 2, 3]. NumPy also provides linear algebra, broadcasting, and statistical functions that lists lack.
42. What is the difference between a shallow copy and a deep copy?
A shallow copy creates a new outer object but keeps references to the same inner objects. A deep copy creates a new outer object and recursively copies every inner object as well.
The difference shows up with nested lists:
import copy
li1 = [['a'], ['b'], ['c']]
li2 = li1 # same object, just a new name
li3 = list(li1) # shallow copy
li4 = copy.deepcopy(li1) # deep copy
li1[0].append('z')
print(li3[0]) # ['a', 'z'] - inner list is shared
print(li4[0]) # ['a'] - fully independentAssignment (li2 = li1) creates no copy at all, so every change to li1 appears in li2. With a shallow copy, appending a new item to li1 does not affect li3, but changing an inner list does. A deep copy is unaffected by either change.

43. What are lambda functions, map() and list comprehensions?
A lambda is a small anonymous function written in one expression. It can take any number of arguments but contains only one expression, so it suits short operations passed to other functions.
map() applies a function to every item in an iterable and returns a lazy iterator. A list comprehension does the same job in a form most Python developers find more readable:
nums = [1, 2, 3]
squares_map = list(map(lambda x: x ** 2, nums)) # [1, 4, 9]
squares_comp = [x ** 2 for x in nums] # [1, 4, 9]In data science work, vectorized pandas or NumPy operations are usually faster than either option, so comprehensions are best kept for plain Python objects.
44. What is the difference between loc and iloc in pandas?
loc selects rows and columns by label, while iloc selects them by integer position. For example, df.loc[10, 'price'] returns the price in the row labeled 10, whereas df.iloc[10, 2] returns the value in the eleventh row and third column.
The two give different results once the index is not a simple 0-to-n range, such as after filtering or sorting. Slicing also differs: loc includes the end label, while iloc excludes the end position, as standard Python slicing does.
45. What is the difference between merge(), join() and concat() in pandas?
All three combine DataFrames, but each suits a different situation:
merge(): It combines DataFrames on one or more key columns, like a SQL join, and supports inner, left, right, and outer joins.
join(): It is a convenience method that joins on the index by default, which is handy when DataFrames share an index.
concat(): It stacks DataFrames vertically (one below the other) or horizontally (side by side) along an axis, without matching on keys.
A quick way to decide is to ask whether you are matching records or stacking them. Matching calls for merge() or join(), while stacking calls for concat().
46. Why is vectorization faster than apply() or loops in pandas?
Vectorized operations run in optimized, compiled code over whole columns at once. By contrast, apply() with a Python function and explicit loops call Python code row by row, which adds significant overhead.
For example, df['total'] = df['price'] * df['qty'] is typically many times faster than computing the same value with apply() across rows. You should reserve apply() for logic that genuinely cannot be expressed with built-in vectorized methods, np.where() or np.select().
47. What are pickling and unpickling?
Pickling is the process of converting a Python object into a byte stream so it can be saved to a file or sent over a network, using pickle.dump(). Unpickling reverses the process with pickle.load(), restoring the original object.
Data scientists often pickle trained models to reuse them later. However, you should never unpickle data from an untrusted source, because a malicious pickle file can run arbitrary code when loaded. For scikit-learn models, joblib is a common alternative, and formats such as ONNX are preferred for sharing models across systems.
48. How is memory managed in Python?
Python manages memory automatically through a private heap that the interpreter controls. Programmers do not allocate or free memory directly; instead, the memory manager allocates space for objects as they are created.
Memory is reclaimed in two ways. Reference counting frees an object as soon as nothing refers to it, and a cyclic garbage collector periodically cleans up groups of objects that refer only to each other. When Python exits, most memory is released, although objects held in reference cycles or by C extensions may not be explicitly cleaned up first.

Data Science Coding Interview Questions (SQL and Python)
Data science coding interview questions are usually solved live or in a shared notebook, so interviewers watch how you think as much as what you write. Talk through your approach first, state any assumptions about the data, and then write the code.
49. Write a SQL query to find the second-highest salary from an employees table.
The simplest approach finds the highest salary below the maximum:
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);A window function generalizes better, because changing one number returns the nth-highest salary:
SELECT DISTINCT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
) ranked
WHERE rnk = 2;DENSE_RANK() is used instead of ROW_NUMBER() so that tied salaries share a rank. Mentioning that choice shows you have thought about duplicates.
50. Write a SQL query to calculate a running total of order value for each customer.
A running total is a cumulative sum, so it calls for SUM() used as a window function:
SELECT
customer_id,
order_date,
amount,
SUM(amount) OVER (
PARTITION BY customer_id
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM orders;PARTITION BY restarts the total for each customer, and ORDER BY sets the sequence in which amounts are added.
51. Write a SQL query to find the top three products by revenue in each category.
This "top N per group" pattern is one of the most frequently asked SQL problems in data science interviews. You aggregate first, rank within each group and then filter:
WITH ranked AS (
SELECT
category,
product_id,
SUM(revenue) AS total_revenue,
ROW_NUMBER() OVER (
PARTITION BY category
ORDER BY SUM(revenue) DESC
) AS rn
FROM sales
GROUP BY category, product_id
)
SELECT category, product_id, total_revenue
FROM ranked
WHERE rn <= 3;The filter must sit outside the common table expression, because window functions cannot be used directly in a WHERE clause.
52. What is the output of this code?
List1 = [1, 2, 3, 4]
List2 = [5, 6, 7, 8]
print(len(list1 + list2))The code raises a NameError, because Python is case-sensitive and list1 has never been defined; only List1 has. Interviewers include traps like this to check how carefully you read code.
If the names matched, the output would be 8. The + operator concatenates two lists into a new list of eight elements, and len() counts them.
53. This function is meant to add three to every number. Find and fix the bug.
def add_three(x):
return x + 5
print(list(map(add_three, [1, 2, 3]))) # prints [6, 7, 8]The function adds five, not three, so its behavior does not match its name. Changing the return line to return x + 3 gives the expected output of [4, 5, 6]. A one-line alternative is [x + 3 for x in [1, 2, 3]], which avoids defining a separate function.
54. Which NumPy function calculates the Euclidean distance between two arrays?
np.linalg.norm() returns the Euclidean distance when you pass it the difference between two arrays:
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([6, 7, 8, 9, 10])
print(np.linalg.norm(x - y)) # 11.180339887498949The result is the square root of the sum of squared differences, which here is the square root of 125. For pairwise distances across many points, scipy.spatial.distance.cdist() is the more efficient choice.
55. Using pandas, find the top three products by revenue in each region.
This is the pandas version of the top-N-per-group problem, and interviewers often ask for it in both SQL and Python to test whether you can move between the two. Group, sum, sort and then take the first three rows of each group:
top3 = (
df.groupby(['region', 'product'], as_index=False)['revenue'].sum()
.sort_values(['region', 'revenue'], ascending=[True, False])
.groupby('region')
.head(3)
)Sorting before the second groupby() matters, because head(3) simply returns the first three rows it finds in each group.
56. Write a Python function that returns the k most frequent words in a text.
collections.Counter handles the counting, so the main work is cleaning the text:
import re
from collections import Counter
def top_k_words(text, k):
words = re.findall(r"[a-z']+", text.lower())
return Counter(words).most_common(k)
print(top_k_words("The cat and the hat and the bat", 2))
# [('the', 3), ('and', 2)]A strong answer also mentions the edge cases you would handle in production, such as removing stop words, dealing with ties, and processing very large texts in chunks.
Generative AI and LLM Interview Questions for Data Scientists
Many data scientist roles now involve building with large language models, so interviewers increasingly add a few GenAI questions to the technical round. They rarely expect research-level depth; instead, they want to know whether you can use these tools sensibly and evaluate their output.
57. How have LLMs changed the work of a data scientist?
LLMs have taken over some routine tasks and opened up new kinds of problems. On the routine side, coding assistants speed up writing SQL, pandas, and boilerplate model code, so data scientists spend less time typing and more time checking and reasoning.
On the new-problem side, unstructured text that once needed custom NLP models can now be classified, summarized or extracted with an LLM and a well-written prompt. The core skills have not disappeared, though. Framing the problem, validating results statistically, and knowing when a simple model beats an LLM matter more than before, because LLM output can be fluent and still wrong.
58. What are embeddings, and how are they used?
Embeddings are numeric vectors that represent text, images or other data so that similar items sit close together in vector space. For example, the embeddings for "refund request" and "money back" will be close, even though the words differ.
Data scientists use embeddings for semantic search, clustering documents, building recommendation features and detecting near-duplicate records. Similarity between two embeddings is usually measured with cosine similarity, and large collections are stored and searched in a vector database.
59. What is retrieval-augmented generation (RAG), and when would you use it instead of fine-tuning?
RAG improves an LLM's answers by first retrieving relevant documents from a knowledge source and then passing them to the model along with the question. The model answers from that context, making responses more current and easier to trace to a source.
RAG suits problems where the knowledge changes often or must be cited, such as answering questions over company policies. Fine-tuning, which retrains the model on your own examples, suits problems where you need a consistent style, format, or specialized behavior that prompting alone cannot achieve. In practice, teams usually try prompting first, then RAG, and turn to fine-tuning only when those fall short.

60. How would you evaluate the output of an LLM-based system?
LLM output is open-ended, so evaluation combines several methods rather than one accuracy score. The usual starting point is a labeled test set of realistic inputs with expected answers or grading criteria.
From there, you can measure output with automatic metrics where they fit (exact match for extraction, or classification metrics for labeling tasks), with an LLM-as-judge set up to score answers against a rubric, and with human review on a sample. For RAG systems, you should evaluate retrieval and generation separately, checking whether the right documents were found and whether the answer stayed faithful to them. Cost and latency per request also belong in the evaluation, since a slightly better model may be too slow or expensive to deploy.
61. What causes hallucinations, and how can you reduce them?
A hallucination is a confident but false or unsupported answer from an LLM. It happens because the model generates the most plausible next words based on patterns in its training data, rather than checking facts.
You can reduce hallucinations by grounding the model with RAG, instructing it to answer only from the provided context and to say when it does not know, and asking for citations to source passages. Lowering the sampling temperature, validating structured outputs against a schema, and adding human review for high-stakes answers also help.
62. What is an AI agent, and how might a data scientist use one?
An AI agent is an LLM-based system that can plan steps, call tools such as a SQL database, a Python environment, or an API, and act on the results to complete a goal. Unlike a chatbot that only replies, an agent works through a task in a loop until it is done or needs input.
A data scientist might build an agent that answers business questions by writing and running SQL, or one that monitors model metrics and drafts an incident summary when drift appears. In such systems, the data scientist defines the tools and guardrails, builds evaluation sets, and measures whether the agent's decisions are reliable enough to trust.

Related: Top 60 Artificial Intelligence Interview Questions & Answers and Top 75 Natural Language Processing (NLP) Interview Questions
Case Study and Problem-Solving Questions
Case study questions are the data scientist questions that test how you approach an open business problem, and there is rarely a single right answer. Interviewers assess your structure, so clarify the goal, state assumptions, break the problem into parts and explain how you would validate each step.
63. Daily active users dropped 10% last week. How would you investigate?
Start by confirming the drop is real rather than a tracking error. Check whether the logging, the dashboard query, or the definition of an "active user" changed around the same date.
If the data holds up, segment the drop to locate it. Break it down by platform, app version, country, acquisition channel, and new versus returning users, because a fall concentrated in one segment points to a specific cause, such as a buggy Android release. Then check internal events (launches, outages, pricing changes) and external ones (holidays, competitor campaigns, seasonality) for the same period. Finally, summarize the most likely cause, its estimated impact, and the next action, since a clear recommendation is what the interviewer is waiting for.
64. How would you build a customer churn prediction model from scratch?
Begin by defining churn precisely, because the definition shapes everything else. For a subscription business, churn might mean no renewal within 30 days of expiry, while for an e-commerce app it might mean no purchase in 90 days.
With the definition settled, build features from data available before the prediction date, such as usage frequency, recent activity trends, support tickets, and payment failures. Train a baseline model like logistic regression, then try gradient boosting, and evaluate with precision and recall on a time-based hold-out set. Most importantly, connect the model to an action: the retention team needs to know who to contact and why, so pair predictions with the main drivers behind each score and measure whether the intervention actually reduces churn.
65. How would you measure the success of a feature that cannot be A/B tested?
Some launches reach every user at once, such as a regulatory change or a company-wide redesign, which rules out a randomized control group. In these cases, you rely on quasi-experimental methods.
A difference-in-differences analysis compares the change in a metric for an affected group against an unaffected group over the same period. If no unaffected group exists, an interrupted time-series analysis compares the actual post-launch trend with a forecast built from the pre-launch trend.
Synthetic control methods are a further option when you can build a comparable group from other markets or segments. Whatever method you choose, state its assumptions clearly, because these approaches give weaker evidence than a true experiment.
66. How would you explain a complex model's results to a non-technical stakeholder?
Lead with the business answer, not the method. For example, say "The model identifies 70% of customers likely to cancel next month, so the retention team can focus on 2,000 accounts instead of 20,000", rather than opening with AUC scores.
After that, explain the main drivers in plain language, using a feature importance chart or SHAP values translated into everyday terms. Be honest about uncertainty and limits, such as which customer groups the model handles poorly. End with a clear recommendation and the decision you need from them to keep the conversation focused.
67. There are 25 horses and a track with five lanes. What is the minimum number of races needed to find the three fastest horses?
The answer is seven races, and the reasoning matters more than the number. You have no stopwatch, so you can only compare horses that race together.
Races 1 to 5: Divide the horses into five groups (A to E) and race each group. This ranks the horses within each group.
Race 6: Race the five group winners. Label the groups by the result, so group A's winner finished first, and group E's winner finished last. A1 is the fastest horse overall.
Eliminate horses: Groups D and E are out, because their winners were beaten by three horses already. From group C, only C1 can still be third; from group B, only B1 and B2 remain; from group A, A2 and A3 remain.
Race 7: Race A2, A3, B1, B2 and C1. The first and second finishers in this race are the second- and third-fastest horses overall.

Puzzles like this appear less often than they used to, but when they do, interviewers want to see a step-by-step elimination rather than a guess.
Behavioral Interview Questions for a Data Scientist
Behavioral questions usually come in the hiring manager round, and they decide close calls between technically similar candidates. The STAR method (Situation, Task, Action, Result) keeps your answers structured and ensures you end with an outcome.
68. Tell me about yourself.
This question opens most interviews, so a prepared 90-second answer pays off. Cover where you are now, the one or two projects that best show your data science skills, and why this particular role is the logical next step.
For example, a fresher might say: "I recently completed a data science program where I built a churn model that reached 0.81 AUC on telecom data. I enjoyed turning the model output into a retention plan, and that is why this analytics role, which sits close to the business, appeals to me." Practice it aloud until it sounds natural, not memorized.
69. Describe a project where your analysis did not go as planned.
Interviewers ask this to see how you handle setbacks and what you learn. Choose a real example where something went wrong for a reason you can explain, such as data leakage discovered late or a model that performed well offline but poorly in production.
Walk through what happened, how you found the problem, and what you changed. The most important part is the lesson, so close with the habit you now follow because of it, such as validating every feature's timestamp before training.
70. Tell me about a time you disagreed with a stakeholder about data.
This question tests whether you can hold your ground on evidence while keeping the relationship intact. A good example involves a stakeholder who wanted a conclusion the data did not support, such as reading a short-term spike as a lasting trend.
Explain how you presented the evidence, what alternative you proposed, and how the decision was finally made. Interviewers respond well to answers in which you listen to the stakeholder's underlying goal and find an analysis that serves it, rather than simply proving them wrong.
Data Science MCQs for Quick Practice
Online assessments often begin with data science MCQs, which test recall under time pressure. Try these ten before reading the answers, and give yourself about 30 seconds per question.
1. Which metric is most useful when false negatives are very costly?
(a) Precision (b) Recall (c) Accuracy (d) Specificity
Answer: (b) Recall, because it measures the share of actual positives the model catches.
2. Which algorithm can shrink some coefficients to exactly zero?
(a) Ridge regression (b) Lasso regression (c) k-NN (d) Naive Bayes
Answer: (b) Lasso regression, because its L1 penalty performs feature selection.
3. What does a p-value of 0.03 mean at a 5% significance level?
(a) The null hypothesis is true (b) There is a 3% chance the null is true (c) You reject the null hypothesis (d) The effect is large
Answer: (c) You reject the null hypothesis, because 0.03 is below 0.05. A p-value says nothing about the effect size.
4. In pandas, which method selects rows by integer position?
(a) loc (b) iloc (c) at (d) query
Answer: (b) iloc.
5. Which SQL function gives tied values the same rank without skipping the next rank?
(a) ROW_NUMBER() (b) RANK() (c) DENSE_RANK() (d) NTILE()
Answer: (c) DENSE_RANK(). RANK() also gives ties the same rank, but it skips the following number.
6. Which technique is unsupervised?
(a) Logistic regression (b) Random forest (c) k-means clustering (d) Linear regression
Answer: (c) k-means clustering, because it groups data without labels.
7. A model scores 99% on training data and 70% on test data. What is the most likely problem?
(a) Underfitting (b) Overfitting (c) Data imbalance (d) Low bias and low variance
Answer: (b) Overfitting, because the large gap shows the model has memorized the training data.
8. What does the Central Limit Theorem describe?
(a) The distribution of individual values (b) The distribution of sample means (c) The correlation between variables (d) The variance of a population
Answer: (b) The distribution of sample means, which approaches a normal distribution as sample size grows.
9. Which Python data type is immutable?
(a) List (b) Dictionary (c) Set (d) Tuple
Answer: (d) Tuple.
10. In a RAG system, what is retrieved before the LLM generates an answer?
(a) Model weights (b) Relevant documents or passages (c) Training labels (d) Hyperparameters
Answer: (b) Relevant documents or passages, which the model uses as context for its answer.
Data Scientist Interview Preparation: A Four-Week Plan
Knowing the questions is only half of data scientist interview preparation; the other half is practicing them in the order interviews test them. A focused four-week plan covers the ground without leaving everything to the final few days.
Week | Focus | What to do |
|---|---|---|
Week 1 | Statistics and fundamentals | Revise distributions, hypothesis testing and A/B test design, and explain each concept aloud in two minutes |
Week 2 | Machine learning | Review core algorithms, evaluation metrics and the bias–variance trade-off, then train two models end to end on a public dataset |
Week 3 | Python and SQL coding | Solve two SQL problems and two pandas problems a day, focusing on joins, window functions and group-wise aggregation |
Week 4 | Case studies, GenAI and mock interviews | Practice metric-drop and modeling cases, build one small LLM or RAG demo, and complete at least two timed mock interviews |

Alongside the plan, a few habits make a clear difference on the day.
Build a resume and portfolio that get you shortlisted
Your resume determines whether you reach the technical rounds, so lead with measurable results from your projects. A line such as "Built a churn model that flagged 70% of churners in the top 20% of scores" says far more than a list of tools.
A one-page resume works best when it links to a GitHub or Kaggle profile with two or three well-documented projects. Each project should state the problem, the data, the approach, and the result, so that a reviewer can understand it in a minute.
Gain hands-on experience with real data
Interviewers can tell quickly whether you have worked with messy, real-world data or only with clean tutorial datasets. Public datasets, Kaggle competitions, and free cloud notebooks let you build that experience even as a fresher.
That experience also gives you honest answers to common follow-up questions, such as "What is your favorite algorithm, and why?" or "What was the hardest data-cleaning problem you faced?"
Related: Top 20 (Interesting) Data Science Projects Ideas With Data
Practice explaining, not just solving
Many candidates know the right answer but lose marks because they cannot explain it clearly. Practice answering questions aloud, ideally in mock interviews with a peer, and time yourself to keep explanations under two minutes.
During coding rounds, the same habit applies. Describe your approach before you write code, so the interviewer can follow your reasoning and steer you if you go off track.
Treat every interview as feedback
Few people get the first data scientist role they apply for, and each interview shows you where to improve. After every round, note the questions you struggled with and add them to your revision list for the following week.
Over a few interviews, that list becomes the most personalized study guide you could have. It turns each rejection into specific preparation for the next attempt.
Frequently Asked Questions
What are the most common data science interview questions?
The most common questions cover overfitting and the bias–variance trade-off, precision and recall, p-values and A/B testing, how specific algorithms such as random forests work, and how to handle missing values. Most interviews also include at least one SQL problem involving joins or window functions.
How should a fresher prepare for a data scientist interview?
A fresher should focus first on statistics, core machine learning algorithms, Python, and SQL, because screening and technical rounds test these most heavily. Building two or three portfolio projects on real data is equally important, since they give you concrete examples to discuss in every round.
Are data science interviews hard?
They are demanding because they cover several skill areas, but they are predictable. Most questions come from a well-known set of topics, so steady, structured practice over four to six weeks prepares most candidates well.
What coding questions are asked in a data science interview?
Data science coding interview questions usually involve SQL (aggregations, joins, window functions, and top-N-per-group problems) and Python with pandas (grouping, merging, and cleaning data). Some companies add basic algorithm problems or ask you to implement a metric, such as precision, from scratch.
Do data scientist interviews include questions on generative AI?
Increasingly, yes. Many interviews now include a few questions on embeddings, retrieval-augmented generation, LLM evaluation, and hallucinations, especially for roles that involve text data or AI products.
How many rounds are there in a data scientist interview?
Most processes have four to six rounds: a recruiter screen, an online assessment, technical and coding interviews, a case study or take-home assignment, and a hiring manager conversation. Start-ups often combine some of these into fewer rounds.
What Python questions are asked in a data science interview?
Data science Python interview questions usually cover core data types (lists, tuples, and dictionaries), NumPy arrays, and pandas operations such as filtering, grouping, and merging. Interviewers also ask about writing efficient code, so expect questions on vectorization, list comprehensions, and memory use.
Are data science MCQs part of the interview process?
Yes, many companies use data science MCQs in an online assessment before the technical rounds. These tests usually cover statistics, machine learning concepts, Python, and SQL, and they are timed, so speed matters as much as accuracy.
How should you answer data science technical interview questions?
Start with a clear one-line definition, then give an example and mention the main trade-off or limitation. This structure shows the interviewer that you understand both what a concept is and when it applies, which is what technical rounds are designed to test.
Conclusion
The 70 data science interview questions above cover what most interviews test: statistics, machine learning, Python, SQL, GenAI, case studies, and behavioral judgment. Working through them in the order of the four-week plan gives you both the knowledge and the practice of explaining it under pressure.
The candidates who stand out are rarely the ones who memorize the most answers. They connect a concept to a business decision, write clean code while explaining their reasoning, and say plainly when a simpler method would do the job better.
If you want structured preparation with mentor support, projects on real data, and placement assistance, explore the AnalytixLabs Data Science Course or book a demo session with our team.