VOOZH about

URL: https://www.geeksforgeeks.org/data-science/data-science-coding-interview-questions/

⇱ Data Science Coding Interview Questions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Data Science Coding Interview Questions

Last Updated : 23 Jul, 2025

To excel in data science coding interviews, it's essential to master a variety of questions that test your programming skills and understanding of data science concepts. We have prepared a list of the Top 50 Data Science Interview Questions along with their answers to ace interviews.

Q.1 Write a function to reverse a string in Python

Reversing a string means flipping its order of characters. You can do this by using Python slicing ([::-1]) or by iterating from the end to the start. This is a common operation in string manipulation.


Output
olleh

Q.2 Check if a string is a palindrome.

Compare the original string with its reversed version to see if they are the same. If they match, it means the string is a palindrome. Return True or False based on this comparison. How can you check a string is palindrome or not in Python:


Output
True

Q 3. Write a function to find the nth Fibonacci number using recursion.

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. Let's see the code to find the nth Fibonacci number:


Output
The 5th Fibonacci number is: 5

Q.4 Find indices of two numbers that add up to a specific target in an array.

First we create a dictionary to store numbers and their indices as you iterate through the array. For each number, check if its complement (target minus the number) exists in the dictionary. If it does, return their indices.

Let's see the code:


Output
[1, 2]

Q.5 Write a Python function to calculate the factorial of a number.

This function calculates the factorial of a number using recursion. If the number is 0 or 1, it returns 1. Otherwise, it multiplies the number by the factorial of the number minus 1.


Output
120

Q.6 How would you count the occurrences of each element in a list?

we use Python's Counter from the collections module to count how often each element appears in a list. Let's do the implementation:


Output
Counter({3: 3, 2: 2, 1: 1})

Q.7 How would you load a CSV file into a Pandas DataFrame?

we can load a csv file into the pandas DataFrame like we have implemented .You can also do this for any csv file

Q.8 Write a function to calculate the element-wise sum of two Numpy arrays.

This adds corresponding elements of two Numpy arrays, creating a new array with the results.


Output
[5 7]

Q.9 How would you extract the diagonal elements of a Numpy matrix?

In this question we have to retreive the diagonal elements in the numpy matrix and we do this with the help of a function called 'np.diagonal'.


Output
[1 5]

Q.10 Write code to reshape a 1D Numpy array into a 2D array with 3 rows.

To reshape 1D Numpy array into 2D array we use the function named as 'array.reshape' and this concept is called reshaping the Array


Output
[[1 2]
 [3 4]
 [5 6]]

Q.11 Write a Python function to calculate the mean, median, and standard deviation of a list of numbers.

we calculate the mean, median, and standard deviation of a list using Numpy's built-in functions. Now we see the implementation of this:


Output
25.0
25.0
11.180339887498949

Q 12. How would you handle missing values in a DataFrame?

fillna() replaces missing values with the mean of each column, while dropna() removes rows with any missing values.

  • Fill with mean:

df.fillna(df.mean(), inplace=True)

  • Drop missing values:

df.dropna(inplace=True)

Q 13. How do you read and write data from a file in Python?

To read and write data from file in Python, we use the built-in open() function, which provides a way to open a file and perform various operations on it, such as reading or writing.

  • Reading a file:
  • Writing a file:

Q 14. Write an SQL query to retrieve all columns from a table named employees where the age is greater than 30.

This query selects all columns from the employees table where the age column value is greater than 30.

SELECT * FROM employees

WHERE age > 30;

Q 15. Write an SQL query to join two tables: orders and customers, where the customer_id in orders matches the id in customers.

The JOIN operation merges orders and customers based on the matching customer_id and id columns.

SELECT orders, customers.

FROM orders

JOIN customers ON orders.customer_id = customers.id;

Q 16. Write an SQL query to find the average salary for each department in a company table, but only for departments with more than 10 employees.

This query calculates the average salary by department but only for those departments that have more than 10 employees, using HAVING to filter the groups.

SELECT department, AVG(salary) AS avg_salary

FROM employees

GROUP BY department

HAVING COUNT(employee_id) > 10;

Q 17. Write an SQL query to find all employees whose salary is greater than the average salary in the employees table.

The subquery (SELECT AVG(salary) FROM employees) calculates the average salary, and the outer query retrieves all employees earning more than that average.

SELECT * FROM employees

WHERE salary > (SELECT AVG(salary) FROM employees);

Q 18. Write an SQL query to find the total sales from the sales table for each product.

This query groups the data by product_id and calculates the total sales (SUM(sales_amount)) for each product.

SELECT product_id, SUM(sales_amount) AS total_sales

FROM sales

GROUP BY product_id;

Q 19. How can you return JSON data in a Flask route?

To return JSON data, you can use the jsonify() function, which converts Python dictionaries to JSON format.This route will return the dictionary as a JSON response.

Q 20. How do you create a simple “Hello, World!” app in Flask?

To create a simple Flask app, you define a route using the @app.route() decorator and return a response from a view function. This will start a basic Flask app that responds with “Hello, World!” when the root URL is accessed

Q 21. Can you explain how Flask handles HTTP methods like GET and POST?

Flask allows you to specify which HTTP methods a route should respond to by using the methods parameter in the @app.route() decorator. By default, Flask routes respond to GET requests, but you can specify others such as POST, PUT, DELETE, etc


Q 22. Create a Class to Represent a Person with Basic Attributes.

  • __init__(self, name, age) initializes the Person object with a name and age.
  • birthday(self) increases the person's age by 1.
  • __str__(self) provides a human-readable string representation of the Person object.

Output
Name: Alice, Age: 30
Name: Alice, Age: 31

Q 23. Explain how a hash table works. Provide an example.

 Hash table is a data structure that stores key-value pairs. It uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.

Q 24. Find the First Non-Repeated Character in a String

Traverse the string and keep track of the frequency of each character. Check which character appears exactly once and return it.


Output
w
None

Q 25. Check if Two Strings are Anagrams of Each Other.


Output
True
False

Q 26. How do you transpose a NumPy array?

Transposing an array means swapping its rows and columns. You can use the transpose method or the .T attribute. Here’s how you can do it:


Output
[[1 4]
 [2 5]]

Q 27 Find the median of two sorted arrays of different sizes.

We merge both arrays, sort them, and return the median value. If the total number of elements is odd, the middle element is the median. If even, it is the average of the two middle elements.


Output
3

Q 28 Implement a sliding window to find the maximum sum of a subarray of a given size k.

We use a sliding window technique to calculate the sum of each subarray of size k. The maximum sum is updated at each step.


Output
9

Q 29. Find the kth smallest element in an unsorted array.

We use the heapq library to find the kth smallest element in unsorted array. Below is the code:


Output
7

Q 30. Generate all possible permutations of a given list of numbers.

We use Python's itertools.permutations to generate all permutations of the given list.


Output
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

Q 31. Simulate a biased coin flip given a fair coin function.

We flip the fair coin twice. If the result is heads-tails or tails-heads, we return a biased value; otherwise, repeat


Output
1

Q 32. Calculate the confidence interval for a given dataset (assume normal distribution).

Confidence Interval is a range where we are certain that true value exists. The selection of a confidence level for an interval determines the probability that the confidence interval will contain the true parameter value. is the We calculate the mean and margin of error using the standard deviation and z-score for the confidence level.

Q 33. Implement the Chi-squared test for independence on a contingency table.

Calculate the Chi-squared statistic by comparing observed and expected frequencies in the contingency table.

Q 34. Generate random numbers following a given probability distribution.

Use numpy.random.choice to generate random numbers based on a given probability distribution.


Output
[2 1 2 2 2 3 1 2 2 2]

Q 35. Implement k-nearest neighbors from scratch.

In this we calculate distances from a given point, sort them, and return the majority label of the k closest points.


Output
1

Q 36. Write a function to calculate the silhouette score for clustering results.

we use sklearn's silhouette_score function to evaluate the quality of clustering. let' see the implementation with code.

Q 37. Perform one-hot encoding of categorical variables in a dataset.

Use pandas.get_dummies to convert categorical columns into one-hot-encoded columns.


Output
 Color_Blue Color_Green Color_Red
0 0 0 1
1 1 0 0
2 0 1 0

Q 38. Implement Principal Component Analysis (PCA) to reduce dimensionality.

Compute covariance matrix, eigenvalues, and eigenvectors to reduce dimensions.


Output
[[-2.82842712]
 [ 0. ]
 [ 2.82842712]]

Q 39 Write a function to handle missing data using multiple imputation.

we use Simple Imputer to replace missing values with the mean or another strategy. Below is the code:

Q 40 Group a dataset by a column and calculate the rolling average for another column.

Use pandas.groupby and rolling to calculate rolling averages.


Output
 Group level_1 Value
0 A 0 NaN
1 A 1 15.0
2 B 2 NaN
3 B 3 35.0


Q 42 Find the most common n-grams in a given text dataset.

Use nltk to extract and count n-grams.

Q 43. Create a pivot table from raw transactional data.

Use pandas.pivot_table to summarize data into a pivot table.


Output
Type X Y
Category 
A 10.0 20.0
B 30.0 NaN

Q 44. Given an integer array, find the sum of the largest contiguous subarray within the array. For example, given the array A = [0,-1,-5,-2,3,14] it should return 17 because of [3,14]. Note that if all the elements are negative it should return zero.

Q 45. Extract entities (e.g., person names, locations) from a given text using Python libraries.

Use spacy for named entity recognition (NER).

Q 46. Write a Python function to tokenize a sentence into words (split by spaces, removing punctuation).

Tokenization is a basic text processing step. Here we tokenize the input text into words, ignoring punctuation.

Q 47. Implement a simple NER function using regular expressions to extract names, locations, and dates.

We’ll use regular expressions to extract potential named entities such as names (capitalized words), locations, and dates.


Q 48. Write a function to convert a color image into grayscale.

Grayscale conversion can be done by averaging the RGB channels or using a weighted sum.

Q 49. Write a custom loss function that calculates the mean squared error but with a twist: it penalizes the model more if the predicted values are too large.

A custom loss function can be written to not only calculate the error but also include additional conditions, like penalizing large predictions.

Q 50 Implement a custom activation function that combines ReLU and sigmoid. Use it in a neural network model.

You are required to define a function combining both ReLU and Sigmoid functions. You will then use this function within a Keras model for neural network training.

Comment

Explore