Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 76 ยท Practice and Review

Coding Interview Questions for Data Science

Coding interview questions for data science with runnable Python, NumPy and SQL answers: recursion, Kadane, LRU cache, BFS and DFS, knapsack, CTEs and more.

Data science interviews usually include a live coding round. It is rarely a hard algorithm contest; it checks that you can write small, correct Python, reason about complexity, handle NumPy shapes and write a clean SQL query under time pressure. This page collects the problems that appear again and again, each with a solution you can run, the time and space cost, and the follow-up an interviewer is likely to ask.

A good routine for every problem: restate it, give a tiny example, say the brute-force idea, then improve it, and finish by testing on an edge case (empty input, one element, duplicates). Try each question on your own before you read the answer. The wider set of conceptual questions is in Data Science Interview Questions, and the practice exercises are in Practice Exercises.

Python fundamentals

1. Write a function that returns the n-th Fibonacci number using recursion. Then make it fast.

The definition is fib(0) = 0, fib(1) = 1, fib(n) = fib(n-1) + fib(n-2). The direct recursion recomputes the same values again and again and takes O(2^n) time. Memoization (caching results, for example with functools.cache) makes each value computed once: O(n) time. An iterative loop with two variables is O(n) time and O(1) space and avoids the recursion limit.

2. How do you count the occurrences of each element in a list?

Use collections.Counter, one line and O(n). The manual version is a dictionary with counts[x] = counts.get(x, 0) + 1. Counter.most_common(k) returns the top k. In pandas the equivalent is Series.value_counts().

3. Explain *args and **kwargs.

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary. They let a function accept a variable number of inputs, and the same stars at a call site unpack a sequence or a dictionary into arguments. They are common in wrappers and decorators that pass everything through to another function.

Python Fibonacci, Counter and *args/**kwargs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Naive recursion makes 21,891 calls for fib(20); the cached version computes each of the values 0 to 90 exactly once.

Arrays, lists and graphs

4. Find the k-th smallest element in an unsorted array.

Sorting works in O(n log n). A max-heap of size k (or heapq.nsmallest) takes O(n log k) time and O(k) space and works on streams. Quickselect partitions around a pivot like quicksort but recurses into only one side: O(n) on average, O(n^2) in the worst case. State which one you pick and why: for small k use the heap, for a one-off on an in-memory list quickselect is the fastest in practice.

5. Find the maximum sum of a contiguous subarray (Kadane's algorithm).

Scan once, keeping best_ending_here: the best sum of a subarray that ends at the current element. At each element you either extend the previous subarray or start fresh: cur = max(x, cur + x). Track the global maximum. O(n) time, O(1) space. Edge cases: an all-negative array returns the largest (least negative) element, not 0, and an empty array needs a defined answer.

6. Detect a cycle in a linked list (Floyd's tortoise and hare).

Move a slow pointer one step and a fast pointer two steps. If there is a cycle, the fast pointer eventually catches the slow one; if the list ends, there is no cycle. O(n) time and O(1) space, compared with O(n) space for the "set of visited nodes" approach. To find where the cycle starts, reset one pointer to the head after they meet and move both one step at a time.

Python k-th smallest, Kadane and Floyd's cycle detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

7. Implement an LRU (least recently used) cache.

A cache of fixed capacity that evicts the entry unused for the longest time, with O(1) get and put. The classic structure is a hash map plus a doubly linked list; in Python an OrderedDict is exactly that. On every get or put, move the key to the "most recent" end; when the size exceeds the capacity, pop from the "oldest" end. Know that functools.lru_cache does this for function results.

8. Implement BFS and DFS on a graph.

Both visit every node once: O(V + E). Breadth-first search uses a queue and visits nodes level by level, so it finds the shortest path in an unweighted graph. Depth-first search uses a stack (or recursion) and goes as deep as it can before backtracking; it suits cycle detection, topological sorting and connected components. Always keep a visited set so cycles do not loop forever. See the DSA tutorial for graphs in depth.

Python LRU cache, BFS and DFS

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

9. Solve the 0/1 knapsack problem with dynamic programming.

Given items with weights and values and a capacity, choose items (each at most once) to maximize total value without exceeding the capacity. Greedy by value per weight is not always optimal. The DP state is dp[w] = the best value achievable with capacity w using the items seen so far. For each item, update w from the capacity down to the item's weight: dp[w] = max(dp[w], dp[w - weight] + value). Going downwards makes sure an item is used at most once. Time O(n * capacity), space O(capacity). See Dynamic Programming in the DSA tutorial.

Python 0/1 knapsack and a greedy counter-example

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

NumPy

10. How do you transpose a NumPy array, and what does broadcasting mean?

a.T (or np.transpose(a, axes)) swaps the axes. It returns a view, not a copy, so no data move. For more than two dimensions, np.transpose(a, (2, 0, 1)) gives the new order of the axes. Broadcasting is how NumPy combines arrays of different shapes without copying: compare shapes from the last axis backwards; two dimensions are compatible when they are equal or one of them is 1, and the size-1 dimension is stretched. A (3, 1) column plus a (4,) row gives a (3, 4) table. A shape such as (3,) and (4,) fails. The usual practical use: subtracting the column means from a 2D array.

Python Transpose and broadcasting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

SQL

11. Use a CTE (WITH clause) to simplify a multi-step query.

A CTE names an intermediate result, so a query reads as a sequence of steps instead of a nest of subqueries. A typical example: first compute each customer's total, then use that result to find the customers above the average total. You can chain several CTEs separated by commas, and later ones can use earlier ones. More background in SQL for Data Science.

Python A two-step CTE with sqlite3

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The average customer total is 148.75, so only Bo (300) and Di (180) are above it. Each step can be tested on its own by running it as a plain SELECT.

Web and deep learning questions (read-only)

Flask and Keras are not available in the browser runner, so the next two answers are code you would run on your own machine.

12. How do you create a simple "Hello, World!" app in Flask, and return JSON from a route?

Create an app, decorate a function with @app.route, and return a string. For JSON, return a dictionary (Flask converts it) or use jsonify. Start it with flask run.

Python
# app.py  (install with: pip install flask)
from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"

@app.route("/api/stats")
def stats():
    return jsonify({"rows": 1200, "columns": 8, "status": "ok"})

@app.route("/api/predict", methods=["POST"])
def predict():
    payload = request.get_json()
    score = 0.1 * payload["age"]            # stand-in for a real model
    return {"score": score}

if __name__ == "__main__":
    app.run(debug=True)                     # http://127.0.0.1:5000

A model is normally loaded once at start-up, not on every request. For a full treatment see the Flask tutorial.

13. Build and train a minimal CNN on image data with Keras.

Stack convolution and pooling layers, flatten, then add dense layers with a softmax output. Compile with an optimizer, a loss and a metric, and call fit.

Python
# pip install tensorflow  (read-only here)
from tensorflow import keras
from tensorflow.keras import layers

(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train[..., None] / 255.0          # (60000, 28, 28, 1), scaled to 0-1
x_test = x_test[..., None] / 255.0

model = keras.Sequential([
    layers.Input(shape=(28, 28, 1)),
    layers.Conv2D(16, 3, activation="relu"),
    layers.MaxPooling2D(),
    layers.Conv2D(32, 3, activation="relu"),
    layers.MaxPooling2D(),
    layers.Flatten(),
    layers.Dropout(0.3),
    layers.Dense(10, activation="softmax"),
])
model.compile(optimizer="adam",
              loss="sparse_categorical_crossentropy",
              metrics=["accuracy"])
model.fit(x_train, y_train, epochs=3, batch_size=128, validation_split=0.1)
print(model.evaluate(x_test, y_test))

Explain the pieces: scaling the pixels, convolution and pooling to extract and shrink features, dropout against overfitting, softmax with the sparse categorical cross-entropy because the labels are integers. A small network like this reaches about 98 percent accuracy on MNIST. The ideas behind it are in the deep learning question page.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is the naive recursive Fibonacci slow?

    fib(n) calls fib(n-1) and fib(n-2), which overlap heavily. Caching the results (memoization) makes each value computed once.
  2. 2. In Kadane's algorithm, what does cur = max(x, cur + x) express?

    If the running sum is negative, adding it only hurts, so the best subarray ending here starts fresh at x.
  3. 3. Why does the 0/1 knapsack loop over capacities from high to low?

    Updating dp[w] from smaller capacities that have already included the current item would use it twice. Going downwards keeps those cells from the previous item.
  4. 4. What is the broadcast result shape of an array of shape (3, 1) plus an array of shape (4,)?

    Shapes are matched from the right: 1 stretches to 4, and the missing axis of the second array is added in front as size 1, which stretches to 3.
  5. 5. What is the advantage of Floyd's cycle detection over storing visited nodes in a set?

    Two pointers need O(1) memory, while a visited set grows with the list. Both take linear time.

Summary

  • Memoize overlapping recursion (Fibonacci), count with Counter, and know that *args and **kwargs collect and unpack arguments.
  • k-th smallest: sort, heap or quickselect; Kadane keeps the best sum ending here; Floyd's two pointers detect cycles in O(1) memory.
  • An LRU cache is a hash map plus recency order (OrderedDict); BFS uses a queue and finds shortest unweighted paths, DFS uses a stack or recursion.
  • 0/1 knapsack: a one-dimensional table updated from high capacity to low.
  • NumPy transpose returns a view; broadcasting compares shapes from the right and stretches size-1 axes.
  • CTEs turn multi-step SQL into readable named steps; Flask and Keras answers are short, standard patterns you should be able to write from memory.

Next: back to the Data Science Interview Questions main page, or test yourself with the Practice Exercises.