Skip to main content

35 Top Data Scientist Interview Questions For All Levels

35 data scientist interview questions with sample answers, from statistics and machine learning to Python and SQL coding and Big Tech examples.
Abid Ali Awan
Abid Ali Awan

Create Your Free Account

Practice and track your progress.

Continue with GoogleBy continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.
Add DataCamp as preferred source on Google

Data scientist interviews ask questions in five areas: statistics and probability (p-values, A/B tests), machine learning (overfitting, bias-variance, evaluation metrics), coding in Python and SQL, product sense (diagnosing a metric drop), and behavioral questions about past projects. Senior roles at tech companies now often add a question on evaluating or shipping LLM-powered features.

Below, I've collected 35 data scientist interview questions with sample answers, from behavioral questions to Python and SQL coding challenges, plus questions Meta, Amazon, and Google have asked. Whether you're a student looking for an internship or a professional aiming for your next role, practicing them prepares you for every interview stage.

If you want to warm up on the statistics questions before working through the rest of this guide, I suggest the Practicing Statistics Interview Questions in Python course, which covers conditional probabilities, A/B testing, and the bias-variance tradeoff.

What Non-Technical Questions Do Data Science Interviews Ask?

Non-technical questions test how you communicate, collaborate, and handle setbacks. Answer them with the STAR method: describe the Situation, the Task, the Action you took, and the Result, ideally with a number. Keep each story under two minutes.

Tell me about a time when you had to explain a complex data concept to someone without a technical background. How did you ensure they understood?

This question assesses your communication skills and ability to simplify complex topics. Here's an example answer:

In my previous role, I had to explain the concept of machine learning to our marketing team. I used the analogy of teaching a child to recognize different types of fruit. Just as you would show a child many examples to help them learn, a machine learning model is trained with data. This analogy helped make a complex concept more relatable and easier to understand.

Describe a project where you had to work with a difficult team member. How did you handle the situation?

This explores your team collaboration skills and conflict resolution abilities. You could answer this with something like: 

In one project, I worked with a colleague who had a very different working style. To resolve our differences, I scheduled a meeting to understand their perspective. We found common ground in our project goals and agreed on a shared approach. This experience taught me the value of open communication and empathy in teamwork.

Can you share an example of a time when you had to work under a tight deadline? How did you manage your tasks and deliver on time?

This question is about time management and prioritization. Here's an example answer: 

Once, I had to deliver an analysis within a very tight deadline. I prioritized the most critical parts of the project, communicated my plan to the team, and focused on efficient execution. By breaking down the task and setting mini-deadlines, I managed to complete the project on time without compromising quality.

Have you ever made a significant mistake in your analysis? How did you handle it and what did you learn from it?

Here, the interviewer is looking at your ability to own up to mistakes and learn from them. You could respond with: 

In one instance, I misinterpreted the results of a data model. Upon realizing my error, I immediately informed my team and reanalyzed the data. This experience taught me the importance of double-checking results and the value of transparency in the workplace.

This shows your commitment to continuous learning and staying relevant in your field. Here's a sample answer: 

I stay updated by reading industry journals, attending webinars, and participating in online forums. I also set aside time each week to experiment with new tools and techniques. Rebuilding a small past analysis with a new library shows me quickly whether it's worth adopting.

Can you tell us about a time when you had to work on a project with unclear or constantly changing requirements? How did you adapt?

This question assesses adaptability and problem-solving skills. As an example, you could say: 

In a previous project, the requirements changed frequently. I adapted by maintaining open communication with stakeholders to understand their needs. I also used agile methodologies to be more flexible in my approach, which helped in accommodating changes effectively.

Describe a situation where you had to balance data-driven decision-making with other considerations (like ethical concerns, business needs, etc.).

This evaluates your ability to consider various aspects beyond just the data. An example answer could be: 

In my last role, I had to balance the need for data-driven decisions with ethical considerations. I ensured that all data usage complied with ethical standards and privacy laws, and I presented alternatives when necessary. This approach helped in making informed decisions while respecting ethical boundaries.

What General Data Science Interview Questions Should You Expect?

What are the assumptions of linear regression?

The four assumptions from a linear regression are:

  1. Linear Relationship: there should be a linear relationship between independent variable x and dependent variable y. 
  2. Independence: the residuals are independent of each other. Violations usually show up in time-series data, where consecutive residuals are correlated. 
  3. Homoscedasticity: at every level of x, the variance should be constant. 
  4. Normality: the residuals are normally distributed.

Normal Q-Q plot showing sample points closely following the theoretical normal line, indicating residual normality

Image from Statology

You can explore the concepts and applications of linear models by taking our Introduction to Linear Modeling in Python course. 

How do you handle a dataset missing several values?

There are various ways to handle missing data. You can:

  1. Drop the rows with missing values.
  2. Drop the columns with several missing values.
  3. Fill the missing value with a string or numerical constant. 
  4. Replace the missing values with the average or median value of the column. 
  5. Predict missing values from the other columns with KNN or iterative (MICE) imputation.
  6. Add an indicator column that flags which values were imputed, so the model can learn from the missingness itself.

Learn how to diagnose, visualize, and impute missing data in our Dealing with Missing Data in Python course.

What is a p-value, and how do you interpret it?

A p-value measures the probability of observing results at least as extreme as the data collected, assuming the null hypothesis is true.

A p-value below your significance level (typically 0.05) gives you evidence to reject the null hypothesis. For example, in an A/B test with a p-value of 0.03, you would see a difference at least this large only 3% of the time if the variant had no effect, which suggests the variant had a real effect.

A common misconception: a p-value does not measure the probability that the null hypothesis is true, only how compatible the data is with it.

What is the difference between a Type I and a Type II error?

These are two types of mistakes in hypothesis testing:

  • Type I error (false positive): Rejecting the null hypothesis when it is actually true. Controlled by your significance level (α). Example: concluding a new model performs better when it actually doesn't.
  • Type II error (false negative): Failing to reject the null hypothesis when it is false. Controlled by statistical power (1 − β). Example: concluding a model shows no improvement when it actually does.

Lowering α reduces Type I errors but increases Type II errors. The right tradeoff depends on the cost of each mistake. In fraud detection or medical screening, a missed case (Type II) usually costs more than a false alarm, so teams accept more false positives.

Learn more in our Hypothesis Testing Made Easy tutorial.

What Technical Questions Come Up in Data Science Interviews?

What are the feature selection methods used to select the right variables?

There are three main methods for feature selection: filter, wrapper, and embedded methods.

Filter Methods

Filter methods are generally used in preprocessing steps. These methods select features from a dataset independent of any machine learning algorithms. They are fast, require fewer resources, and remove duplicated, correlated, and redundant features.

Filter method flow: set of all features, selecting the best feature, learning algorithm, and performance

Image by Author

Some techniques used are:  

  • Variance Threshold
  • Correlation Coefficient
  • Chi-Square test
  • Mutual information

Wrapper Methods

In wrapper methods, we train the model iteratively using a subset of features. Based on the results of the trained model, more features are added or removed. They are computationally more expensive than filter methods but provide better model accuracy. 

Wrapper method loop: generate a subset, test with learning algorithm, repeat to select the best feature set

Image by Author

Some techniques used are:

  • Forward selection
  • Backward elimination
  • Bi-directional elimination
  • Recursive feature elimination (RFE)

Embedded Methods

Embedded methods combine the qualities of filter and wrapper methods. The feature selection algorithm is blended as a part of the learning algorithm, providing the model with a built-in feature selection method. These methods are faster, like the filter methods, accurate like the wrapper methods, and take into consideration a combination of features as well.  

Embedded method: generating subsets, training the learning algorithm, and measuring performance happen inside one selection loop

Image by Author

Some techniques used are:

  • Regularization
  • Tree-based methods

Learn the most commonly tested feature selection techniques in our Python Feature Selection Tutorial.

How can you avoid overfitting your model?

Overfitting refers to a model that is trained too well on a training dataset but fails on the test and validation dataset.

You can avoid overfitting by:

  1. Keeping the model simple by decreasing the model complexity, taking fewer variables into account, and reducing the number of parameters in neural networks.
  2. Using cross-validation techniques.
  3. Training the model with more data.
  4. Using data augmentation that increases the number of samples. 
  5. Using ensembling (Bagging and Boosting)
  6. Using regularization techniques to penalize certain model parameters if they're likely to cause overfitting.

Overfitting fixes change the model, the data, or how you evaluate

For a deeper guide on preventing overfitting, read What is Overfitting? and our tutorial on Regularization in Machine Learning.

What is the bias-variance tradeoff?

The bias-variance tradeoff describes two sources of prediction error that pull in opposite directions. Bias is error from a model too simple to capture the pattern, which leads to underfitting. Variance is error from a model so sensitive to its training data that it fits the noise, which leads to overfitting.

Making a model more complex lowers bias and raises variance, so the goal is the complexity at which error on unseen data is lowest. You find it with cross-validation and move along the tradeoff with regularization, pruning, or ensembling. Our bias-variance tradeoff tutorial has worked examples.

When would you use precision instead of recall?

Choose the metric by the cost of each mistake. Precision is the share of predicted positives that are correct, so prioritize it when false positives are expensive, like a spam filter that sends real email to junk. Recall is the share of actual positives the model finds, so prioritize it when misses are expensive, like fraud detection or cancer screening.

When you need both, report the F1 score (their harmonic mean) or plot a precision-recall curve to choose a threshold. On imbalanced data, both tell you far more than accuracy. Our precision vs. recall guide covers both in depth, and our F1 score tutorial explains the combined metric.

What is data leakage, and how do you prevent it?

Data leakage happens when information that won't exist at prediction time ends up in training, so the model scores far better in validation than it does in production. The two common forms are target leakage, where a feature is derived from the outcome (a "refund issued" flag in a churn model), and train-test contamination, where preprocessing sees the test data.

You prevent it by:

  • Splitting the data before any scaling, imputation, or feature selection, and fitting those steps on the training set only. scikit-learn pipelines do this for you.
  • Splitting time series by date, so the model never trains on the future.
  • Checking every feature for whether it would exist at the moment of prediction.

The Model Validation in Python course covers the validation techniques that catch these problems.

What are the types of relationships in SQL?

There are four main types of SQL relationships:

  • One to One: it exists when each record of a table is related to only one record in another table. 
  • One to Many and Many to One:  it is the most common connection, where each record in a table is linked to several records in another.  
  • Many to Many: it exists when each record of the first table is related to more than one record in the second table, and a single record in the second table can be related to more than one record of the first table. 
  • Self-Referencing Relationships: it occurs when a table has to declare a connection with itself.

Learn how to explore the tables, the relationships between them, and the data stored in them by completing our Exploratory Data Analysis in SQL course.

What is dimensionality reduction, and what are its benefits?

Dimensionality reduction is a process that converts the dataset from several dimensions into fewer dimensions while maintaining similar information. 

PCA diagram showing 3D clustered data points projected onto a 2D plane, separating classes into distinct groups

Image by Author | Graphs by howecoresearch

Benefits of dimensionality reduction:

  1. Compressing the data and reducing the storage space. 
  2. Reduce computational time and allow us to perform faster data processing.  
  3. It removes redundant features, if any. 

Understand the concept of reducing dimensionality and master the techniques by practicing using Dimensionality Reduction in Python course.

What is the goal of A/B testing, and how do you design a test?

A/B testing diagram comparing two app versions, A and B, to determine which performs better

Image by Author

A/B testing tells you whether a change causes a measurable improvement, so product decisions rest on evidence rather than opinion. It is a randomized experiment: users are split at random between the current version (A) and a variant (B), and you compare a metric chosen in advance.

Interviewers usually follow up by asking how you would design one. A strong answer covers:

  1. Hypothesis and metrics: one primary metric, plus guardrail metrics that must not get worse.
  2. Sample size: a power analysis from the minimum effect worth detecting, the significance level (often 0.05), and the power (often 80%).
  3. Run length: at least one full weekly cycle, without stopping early the first time the result looks significant.
  4. Analysis: a significance test and a confidence interval for the effect, plus a check that the traffic split matches the plan (sample ratio mismatch).

Learn how to design, run, and analyze experiments in our A/B Testing in Python course.

What Coding Questions Do Data Science Interviews Include?

Coding rounds test whether you can turn a plain-language problem into working Python or SQL. Talk through your approach before you write code, and state your assumptions about the input.

Given a dictionary consisting of many roots and a sentence, stem all the words in the sentence with the root forming it.

Stemming is commonly used in text and sentiment analysis. In this question, you will write a Python function that will convert certain words from the list to their root form - Interview Query.

Input:

The function will take two arguments: list of root words and sentence.  

roots = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"

Output:

It will return the sentence with root words. 

"the cat was rat by the bat"

Before you jump into writing code, you need to understand that we will perform two tasks: check if the word has a root and replace it. 

  1. You will split the sentence into words.
  2. Run the outer loop over each word in the list and the inner loop over the list of root words.
  3. Check if the word starts with the root. Python strings have a startswith() method for this. 
  4. If the word starts with the root, replace the word with the root using a list index. 
  5. Join all of the words to create a sentence. 
roots = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"


def replace_words(roots, sentence):
    words = sentence.split(" ")

    # looping over each word
    for index, word in enumerate(words):
        # looping over each root
        for root in roots:
            # checking if words start with root
            if word.startswith(root):
                # replacing the word with its root
                words[index] = root
    return " ".join(words)


replace_words(roots, sentence)


# 'the cat was rat by the bat'

How do you check if a string is a palindrome?

Given the string text, return True if it’s a palindrome, else False.

After lowering all letters and removing all non-alphanumeric characters, the word should read the same forward and backward.

Palindrome check examples: Anna and Radar and Level pass, Abid and Data fail

Image by Author

Python gives you two ways to reverse a string. You can either treat the string as iterable and reverse it using text[::-1] or use the built-in reversed(text) method.

  1. First, you will lower the text.
  2. Clean the text by removing non-alphanumeric characters using regex. 
  3. Reverse the text using [::-1].
  4. Compare the cleaned text with the reversed text.  
import re

def is_palindrome(text):
    # lowering the string
    text = text.lower()

    # removing every non-alphanumeric character
    text = re.sub(r"[^a-z0-9]", "", text)

    # reversing and comparing the string
    return text == text[::-1]

In the second method, you will just replace reversing the text with ''.join(reversed(text)) and compare it with cleaned text. 

def is_palindrome(text):
    # lowering the string
    text = text.lower()

    # removing every non-alphanumeric character
    text = re.sub(r"[^a-z0-9]", "", text)

    # reversing the string
    reversed_text = "".join(reversed(text))
    return text == reversed_text

Results:

We will provide the list of the word to the is_palindrome() function and print the results. As you can see, even with special characters, the function has identified “Level” and “Radar” as palindromes. 

# Test cases
test_words = ['Anna', '**Radar****', 'Abid', '(Level)', 'Data']

for text in test_words:
    print(f"Is {text} a palindrome? {is_palindrome(text)}")


# Is Anna a palindrome? True
# Is **Radar**** a palindrome? True
# Is Abid a palindrome? False
# Is (Level) a palindrome? True
# Is Data a palindrome? False

Prepare for your next coding interviews by Practicing Coding Interview Questions in Python with our interactive course. For deeper Python coding prep, see our 41 Top Python Interview Questions & Answers For 2026.

How do you find the second-highest salary in SQL?

Finding the maximum takes one function call. The second-highest, or nth-highest, value takes one more idea: skip past the values above it.

In the question, you are provided with the database table that consists of id and base_salary. You will be writing the SQL query to find the second-highest salary. 

Table of employee id and base_salary values used to find the second-highest salary with SQL

Image by Author

In this query, you will find the unique values and order them from highest to lowest. Then, you will use LIMIT 1 to display only the highest value. In the end, you will offset the value by 1 to display the second-highest number. 

You can also change the OFFSET value to get nth highest salary. 

SELECT DISTINCT base_salary AS "Second Highest Salary"
FROM employee
ORDER BY base_salary DESC
LIMIT 1
OFFSET 1;

The second highest base salary is 8,500.

SQL query result showing the second highest salary value, 8500

Interviewers often ask for a second solution that also works per group, such as the second-highest salary in each department. A window function handles both, and DENSE_RANK() gives tied salaries the same rank:

SELECT DISTINCT base_salary AS "Second Highest Salary"
FROM (
  SELECT base_salary,
         DENSE_RANK() OVER (ORDER BY base_salary DESC) AS salary_rank
  FROM employee
) AS ranked
WHERE salary_rank = 2;

Add PARTITION BY department_id inside OVER() to get one answer per department. Practice ranking and running totals in the PostgreSQL Summary Stats and Window Functions course.

How do you find duplicate emails in SQL?

In this question, you will write a query to display all of the duplicate emails. 

Table of employee emails with matt@hotmail.com appearing twice, the duplicate to find

Image by Author

In this query, you will display an email column and group the table by email. After that, we will use the HAVING clause to find emails that are mentioned more than once. 

WHERE filters rows before grouping, while HAVING filters groups after the aggregation, which is why the count condition goes in HAVING.

SELECT email
FROM employee_email
GROUP BY email
HAVING COUNT(email) > 1;

Only “[email protected]” occurs more than once.

Query result showing email column with matt@hotmail.com as the duplicate entry

Write maintainable SQL code to answer business questions by taking the Applying SQL to Real-World Problems course.

What AI and LLM Questions Do Data Scientists Get in 2026?

Interviews for data science roles at tech companies increasingly include one or two questions on large language models. They check whether you can judge when an LLM fits a problem and how you would measure whether it works, not whether you can train one.

When would you use RAG instead of fine-tuning?

Use retrieval-augmented generation (RAG) when the model needs knowledge it doesn't have, especially knowledge that changes, like product documentation or internal policies. RAG retrieves relevant documents at query time and passes them to the model, so updating its knowledge means updating the document store, and answers can cite their sources.

Use fine-tuning when you need to change the model's behavior rather than its knowledge: a consistent output format, a domain's style, or a narrow classification task. It needs labeled examples and retraining whenever requirements change, and many production systems combine the two. Our tutorial on RAG vs. fine-tuning walks through both with code.

How would you evaluate an LLM-powered feature?

Accuracy alone doesn't work for generated text, so I would evaluate at three levels:

  1. Offline test set: real inputs with reference answers or grading criteria, scored for correctness and groundedness (does the answer stick to its sources?). An LLM judge can score at scale once you've checked it against human ratings.
  2. Failure modes: hallucinations, refusals, and off-policy outputs, each tracked separately.
  3. Online impact: an A/B test on the user behavior the feature should change, such as task completion, plus latency and cost per request.

See our guide to LLM evaluation for metrics and tools.

How do you monitor a model after deployment?

Track three things: the input data, the predictions, and the business outcome. Data drift is a change in the input distribution, which you detect by comparing live features with the training data, for example with the Population Stability Index or a Kolmogorov-Smirnov test. Concept drift is a change in the relationship between inputs and target, which only shows up when you compare predictions with actual outcomes.

Set alerts on these signals, and retrain on a schedule or when performance drops below an agreed threshold. Our tutorial on data drift and model drift covers the detection methods in Python.

For more practice, see our LLM interview questions and generative AI interview questions.

What Do Meta, Amazon, and Google Ask in Data Science Interviews?

Big Tech interviews mix the technical questions above with product and metric questions about the company's own products, as the examples below show.

Meta Data Science Interview Questions

Facebook composer, the posting tool, dropped from 3% posts per user last month to 2.5% posts per user today. How would you investigate what happened?

Facebook's Create Post composer UI used to illustrate the post composer feature in the interview question

Image by Author

The post from a month ago dropped from 3% to 2.5% today. Before you jump to a conclusion, you need to clarify the context around the problem. 

You need to ask questions:

  • Is it a weekday today?
  • Was a month ago from today a weekend?
  • Are there special occasions, events, or seasonality? 
  • Is there a gradual downward trend or a one-time occurrence?

Then break the metric into its parts. Posts per user is posts divided by users, so the drop comes from fewer posts, more users who post less (for example, a wave of new sign-ups), or both. Segment each part by platform, country, app version, and user tenure to find where the drop is concentrated.

Investigate a posts-per-user drop in three steps

What do you think the distribution of time spent per day on Facebook looks like? What metrics would you use to describe that distribution?

In terms of the distribution of time spent per day on Facebook, one can assume that there might be two groups:

  1. People who scroll through the feed fast without spending too much time.
  2. Super users who spend large amounts of time on Facebook.

For the second part, you have to use statistical vocabulary to describe the distribution, such as:

  1. Center: mean, median, and mode
  2. Spread: standard deviation, interquartile range, and range
  3. Shape: skewness, kurtosis, and uni or bimodal
  4. Outliers

Given a dataset of test scores, write pandas code to return the cumulative percentage of students that received scores within the buckets of <50, <75, <90, <100.

In this question, you will write pandas code to first divide the score into various buckets and then calculate the percentage of the students getting the score in those brackets. 

Input:

Our dataset has user_id, grade, and test_score columns. 

Sample dataframe with user_id, grade, and test_score columns used for bucketing scores

Image by Author 

Output:

You will be writing the function that will use grade and test_score columns. And display the DataFrame with grades, bucket scores, and cumulative percentage of students getting bucket scores.  

Table showing cumulative percentage of students by grade and test score bucket

Image by Author

  1. You will use the pandas.cut() function to convert scores into bucket scores using bins and labels of buckets. 
  2. Calculate the size of each group (grade and test_score).
  3. For calculating the percentage, we need numerator (cumulative sum) and denominator (sum of all values).
  4. Converting the fraction value into a proper percentage by multiplying it by 100 and adding “%”.
  5. Reset index and rename the column as "percentage".
import pandas as pd

def bucket_test_scores(scores):
    bins = [0, 50, 75, 90, 101]  # 101 so a perfect score of 100 lands in "<100"
    labels = ["<50", "<75", "<90", "<100"]

    # converting the scores into buckets
    buckets = pd.cut(scores["test_score"], bins=bins, labels=labels, right=False)

    # counting students per grade and bucket, keeping empty buckets
    counts = scores.groupby(["grade", buckets], observed=False).size()

    # cumulative share of students within each grade
    cumulative_share = counts.groupby("grade").cumsum() / counts.groupby("grade").transform("sum")

    # formatting as a rounded percentage
    percentage = (cumulative_share * 100).round().astype(int).astype(str) + "%"
    return percentage.reset_index(name="percentage")


bucket_test_scores(scores)

The function returns one row per grade and bucket, with the cumulative percentage of students.

Table showing cumulative percentage of students by grade and test score bucket in pandas

Learn how to clean data, calculate statistics, and create visualizations with Data Manipulation with pandas course. For a deeper dive, see our guide to the Top 35 Machine Learning Interview Questions For 2026.

Amazon Data Science Interview Questions

What is a confidence interval?

A confidence interval is a range of plausible values for an unknown population parameter, such as a mean or a conversion rate, computed from a sample.

Bell curve showing a 95% confidence interval around the population mean μ within sample means distribution

Image from omnicalculator

A 95% confidence level 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 this particular interval contains it. The interval is the estimate plus or minus a margin of error, which shrinks as the sample grows.

You can use confidence intervals for various statistical estimates, such as proportions, population means, differences between population means or proportions, and estimates of variation among groups.

Build the statistics foundation by completing our Statistical Thinking in Python (Part 1) course.

How do you handle an imbalanced dataset?

In the unbalanced dataset, the classes are distributed unequally. For example, in the fraud detection dataset, there are only 400 fraud cases compared to 300,000 non-fraud cases. The unbalanced data will make the model perform worse in detecting fraud. 

Scatter plot showing imbalanced classes, with far fewer yellow minority points than purple majority points

Image by Author

To handle imbalanced data, you can use:

  1. Undersampling
  2. Oversampling
  3. Creating synthetic data
  4. Combination of under and over sampling

Undersampling

It removes samples from the majority class until both classes are the same size.

In the fraud detection dataset, both classes will be equal to 400 samples. You can use imblearn.under_sampling to resample your dataset with ease.

from imblearn.under_sampling import RandomUnderSampler
RUS = RandomUnderSampler(random_state=1)
X_US, y_US = RUS.fit_resample(X_train, y_train)

Oversampling

It duplicates samples from the minority class until both classes are the same size. In the fraud example, both classes end up with 300,000 samples.

from imblearn.over_sampling import RandomOverSampler

ROS = RandomOverSampler(random_state=0)
X_OS, y_OS = ROS.fit_resample(X_train, y_train)

Creating synthetic data

The problem with repetition is that it does not provide extra information, which will result in the models' poor performance. To counter it, we can use SMOTE (Synthetic Minority Oversampling technique) to create synthetic data points. 

from imblearn.over_sampling import SMOTE

SM = SMOTE(random_state=1)
X_OS, y_OS = SM.fit_resample(X_train, y_train)

Combination of under and over sampling

To improve model biases and performance, you can use a combination of over and under-sampling. We will use SMOTE for over-sampling and ENN (Edited Nearest Neighbors) for cleaning. 

The imblearn.combine provides us with various functions that automatically perform both sampling functions. 

from imblearn.combine import SMOTEENN

SMTN = SMOTEENN(random_state=0)
X_OUS, y_OUS = SMTN.fit_resample(X_train, y_train)

Two follow-ups interviewers expect: resample the training set only, never the test set, and don't judge the model by accuracy. With 400 fraud cases among 300,400 transactions, a model that always predicts "not fraud" scores 99.9% accuracy, so report precision, recall, or the area under the precision-recall curve instead. Many scikit-learn models also accept class_weight="balanced", which penalizes minority-class errors more without resampling at all.

Write a query to return the total number of sales for each product for the month of March 2022.

As a data scientist, you will be writing a similar type of query to extract the data and perform data analysis. In this challenge, you will either use the WHERE clause with comparison signs or WHERE with BETWEEN clause to perform filtering.

Table: orders

Orders table schema with columns order_id, product_id, customer_id, order_dt, qty, unit_price_usd, and channel

Image by Author

Sample output:

Sample query output showing product_id and total sales sum for March 2022

Image by Author

  1. You will display product id and sum of the quantity from the orders table. 
  2. Filter out the data from date ‘2022-03-01’  to '2022-04-01' using WHERE and AND clause. You can also use BETWEEN to perform a similar action. 
  3. Use a group by product_id to get the total number of sales for each product.
SELECT product_id,
      SUM(qty)
FROM orders
WHERE order_dt >= '2022-03-01'
  AND order_dt < '2022-04-01'
GROUP BY product_id;

Google Data Science Interview Questions

If the labels are known in a clustering project, how would you evaluate the performance of the model?

When you have the true labels, compare the cluster assignments with them using external metrics. Plain accuracy doesn't work, because cluster IDs are arbitrary: cluster 0 might correspond to class 2. Use metrics that ignore label names, such as the Adjusted Rand Index (ARI), normalized mutual information (NMI), or V-measure:

from sklearn import metrics
from sklearn.cluster import KMeans

model = KMeans(n_clusters=3, random_state=0).fit(X)
predicted = model.labels_

metrics.adjusted_rand_score(y_true, predicted)          # 1.0 = perfect match, about 0 = random
metrics.normalized_mutual_info_score(y_true, predicted)  # 0 to 1, higher is better
metrics.v_measure_score(y_true, predicted)               # 0 to 1, higher is better

Interviewers often follow up with the case where labels are missing. Then you fall back on internal metrics, which measure how compact and well separated the clusters are.

Scatter plot showing three distinct clusters identified by a clustering algorithm

Image from scikit-learn documentation

The three most common internal metrics are:

  • Silhouette Score
  • Calinski-Harabasz Index
  • Davies-Bouldin Index

Silhouette Score

It is calculated using the mean intra-cluster distance and the mean nearest-cluster distance. 

We can use scikit-learn to calculate the metric. The Silhouette Score is between -1 to 1, where higher scores mean lower similarity between groups and distinct clusters. 

from sklearn import metrics
from sklearn.cluster import KMeans

model = KMeans(n_clusters=3, random_state=0).fit(X)
labels = model.labels_

metrics.silhouette_score(X, labels)

Calinski-Harabasz Index

It calculates distinctiveness between groups using between-cluster dispersion and within-cluster dispersion. The metric has no bound, and just like Silhouette Score, a higher score means better model performance. 

metrics.calinski_harabasz_score(X, labels)

Davies-Bouldin Index

It calculates the average similarity of each cluster with its most similar cluster. Unlike other metrics, a lower score means better model performance and better separation between clusters.   

metrics.davies_bouldin_score(X, labels)

Learn how to apply hierarchical and k-means clustering in our Cluster Analysis in Python course.

There are four people in an elevator and four floors in a building. What’s the probability that each person gets off on a different floor?

Diagram of 4 people in an elevator with 4 floors, illustrating the probability interview question

Image by Author

We will use:

Formula for probability: F factorial divided by P raised to the power F

  • F = Number of floors
  • P = Number of people

To solve this problem, we need to first find the total number of ways to get off the floors: 44 = 4x4x4x4 = 256 ways.

After that, calculate the number of ways each person can get off on a different floor: 4! = 24.

To calculate the probability that each person gets off on a different floor, we need to divide the number of ways each person gets off on a different floor with the total number of ways to get off the floors. 

24/256 = 3/32

Learn strategies for answering tricky probability questions with R by taking our Probability Puzzles in R course.

Write a function to generate N samples from a normal distribution and plot the histogram.

To generate N samples from the normal distribution, you can use NumPy (np.random.default_rng().normal(size=N)) or SciPy (scipy.stats.norm.rvs(size=N)).

To plot a histogram, you can either use Matplotlib or Seaborn. 

  1. Generate the samples with a NumPy random generator. 
  2. Plot histogram with KDE using Seaborn. 
  3. Plot histogram for 10K samples and return the Numpy array. 
import numpy as np
import seaborn as sns

N = 10_000

def norm_dist_hist(N):
    # generating normal distribution samples with a seeded generator
    rng = np.random.default_rng(seed=42)
    x = rng.normal(size=N)
    # Plotting histogram
    sns.histplot(x, bins = 20, kde=True);
    return x
   
X = norm_dist_hist(N)

Histogram with KDE overlay of 10,000 samples from a normal distribution, showing a bell-shaped curve centered at 0

Learn how to create informative and attractive visualizations in seconds by completing Introduction to Data Visualization with Seaborn course.

How Do You Prepare for a Data Science Interview?

Breakdown of data science interview question types: 46% stats/ML, 32% coding, 12% behavioral, 10% product sense

Image by Author

The data science interviews are divided into four to five stages. You will be asked about statistical and machine learning, coding (Python, R, SQL), behavioral, product sense, and sometimes leadership questions. 

You can prepare for all stages by:

  1. Researching the company and job responsibilities: it will help you prioritize your effort in a certain field of data science. 
  2. Reviewing past portfolio projects: the hiring manager will assess your skills by asking questions about your projects. 
  3. Revising the data science fundamentals: probability, statistics, hypothesis testing, descriptive and bayesian statistics, and dimensionality reduction. Cheat sheets are the best way to learn the basics fast. 
  4. Practicing coding: take assessment tests, solve online code challenges, and review most asked coding questions. 
  5. Practicing on end-to-end projects: brush up on data cleaning, manipulation, analysis, and visualization. 
  6. Reading the most common interview questions:  product sense, statistical, analytical, behavioral, and leadership questions. 
  7. Taking mock interviews: practice an interview with a friend, improve your statistical vocabulary, and become confident. 

Read the Data Science Interview Preparation blog to learn what to expect and how to approach the interview.

Final Thoughts

Most data scientist interviews come back to four skills: reasoning with statistics, building and evaluating models, writing clean Python and SQL, and explaining results to people who don't share your background. In 2026, a question on LLM-powered features increasingly joins them.

Practice by answering out loud, timing your coding solutions, and tying every answer to a business decision. If you need to fill gaps first, the Associate Data Scientist in Python track covers the fundamentals, and the Data Scientist Certification gives employers evidence of your skills.

To keep practicing after this article, I recommend the Practicing Machine Learning Interview Questions in Python course, where you can work through machine learning interview questions in Python and check your answers.

Data Science Interview FAQs

What are the four major components of data science?

The four major components of data science are business understanding and data strategy; data preparation (cleaning, imputing, and validating); data analysis and modeling; and data visualization and operationalization. Interviewers often ask you to walk through a past project along these stages, from the business question to the result in production.

Are data science interviews hard?

They cover a lot of ground. You need to show skill in statistics and probability, Python and SQL coding, machine learning, product sense, and communication, often across four or five rounds. Practicing questions from each area and explaining your reasoning out loud prepares you for most of them. Our Data Science Interview Preparation guide has a study plan.

Is data science a stressful job?

It depends. Your whole team/company may rely on you to provide analysis and actionable information. In some cases, you have to wear multiple hats, such as data engineer, data analyst, machine learning engineer, MLOps engineer, data manager, and team lead. Some individuals find this exciting and challenging, while others find it stressful and overwhelming at times.

Is one year of learning enough for data science?

It depends on your starting point. A software engineer or analyst who already codes can often become job-ready within a year, while someone starting from zero usually needs longer. The Associate Data Scientist in Python track covers the fundamentals in about 90 hours; add portfolio projects to show what you can do.

Is data science math heavy?

Moderately. You need working knowledge of statistics and probability, linear algebra to understand models such as PCA and regression, and some calculus for how models are optimized. Day-to-day work leans more on statistics, experiment design, and interpreting results than on deriving formulas, so most interviews test applied statistics rather than proofs.

Does a career in data science offer a good salary?

Yes. The US Bureau of Labor Statistics reports a median annual wage of $120,230 for data scientists in May 2025 and projects employment to grow 35% from 2025 to 2035, much faster than average. Pay varies by company, location, and experience. See How to Become a Data Scientist for career paths.

How can I prove my data science skills to employers?

Show your work. Build two or three real-world data science projects you can explain in depth, and back them with a certification. DataCamp's Data Scientist Certification tests your skills with timed exams and a practical exam on a real-world data project.

What questions are asked in a data scientist interview?

Data scientist interviews ask about statistics and probability, machine learning, Python and SQL coding, product sense, and past projects. Expect questions on p-values, A/B test design, overfitting and evaluation metrics, a live coding task, a metric-drop case, and STAR-format behavioral stories. Senior roles at tech companies often add a question on evaluating LLM-powered features.

Topics

Related

⌂ 换网址