Skip to main content
LearnMLAcademy
Advanced10 min read

Python Coding for AI/ML Interviews

Practice essential Python coding problems asked in machine learning interviews, with skill checklists, worked cases, and role-specific interview drills.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Python interview rounds for AI and data roles usually test clear data manipulation, correctness, complexity, and communication—not obscure competitive-programming tricks. A strong answer begins by clarifying input and output before writing code.

The expanded coding set mixes AI/data manipulation with classic big-tech DSA patterns reported in ML-engineer loops, so you practice both role-specific reasoning and the algorithmic coding bar.

UPDATED FOR 20266 current big-tech signals moved to the top

This is the expanded interview-preparation version

Current, research-driven questions are shown first so you can immediately see what changed. Each question keeps the detailed answer, example, likely follow-up, and weak-answer warning.

15
solved exercises

What you will be able to do

  • Clarify assumptions before coding
  • Select simple Python data structures
  • Write and explain AI/data plus DSA exercises
  • Analyze time and space complexity
  • Test edge cases and discuss follow-ups

A reliable coding answer begins before typing

Turn an ambiguous prompt into a testable solution

Restate problem
Clarify inputs
Choose structure
Walk example
Implement
Test edges
Complexity + follow-up
How to read it: State assumptions, choose a simple data structure, test edges, then discuss complexity and alternatives.

The interview coding contract

Say this before and after implementation

Say this before and after implementation
StageObservable reasoning
AssumptionsInput type, missing values, duplicates, ordering, numerical limits
ApproachWhy this data structure and what invariant it maintains
ImplementationSmall functions, clear names, explicit failures
VerificationNormal case, empty input, boundary values, duplicates
ComplexityTime and auxiliary space in terms of input size
Follow-upHow requirements or scale would change the design

15 solved interview exercises

Current big-tech coding patterns are shown first, followed by the core AI/data exercises.

RUNNABLE PYTHON2026 SIGNAL

Recent Google and Meta MLE question banks include merge-sorted-list style coding patterns.

10. Merge two sorted lists

Problem: Merge two ascending integer lists into one sorted list without sorting the combined result again.

Reasoning: Use two pointers. At each step append the smaller current value, then append any remaining suffix.

RUNNABLE PYTHON
def merge_sorted(a, b):
    i = j = 0
    out = []
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            out.append(a[i]); i += 1
        else:
            out.append(b[j]); j += 1
    out.extend(a[i:])
    out.extend(b[j:])
    return out

print(merge_sorted([1, 4, 7], [2, 3, 8]))
Complexity: O(n+m) time and O(n+m) output space.
Edge cases: Empty input, duplicates, already-disjoint ranges, and whether in-place mutation is allowed.
Follow-up: Merge k sorted lists efficiently using a heap.
RUNNABLE PYTHON2026 SIGNAL

Bracket-validation variants appear in recent Meta, Apple, and Amazon-style coding question banks.

11. Validate brackets

Problem: Return True when (), [], and {} are correctly balanced and nested.

Reasoning: Push opening brackets onto a stack. Every closing bracket must match the most recent unmatched opener.

RUNNABLE PYTHON
def valid_brackets(text):
    pairs = {')': '(', ']': '[', '}': '{'}
    stack = []
    for ch in text:
        if ch in '([{':
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return not stack

print(valid_brackets('{[()]}'))
Complexity: O(n) time and O(n) worst-case stack space.
Edge cases: Ignore or reject non-bracket characters according to the contract.
Follow-up: Return the index of the first mismatch instead of a boolean.
RUNNABLE PYTHON2026 SIGNAL

Nearest-common-ancestor questions are reported in recent Google, Meta, and Apple MLE banks.

12. Lowest common ancestor in a binary tree

Problem: Given a binary tree and two node values, return their lowest common ancestor.

Reasoning: Recurse. If the current node matches either target, return it. If left and right both return a node, the current node is the lowest common ancestor.

RUNNABLE PYTHON
class Node:
    def __init__(self, value, left=None, right=None):
        self.value, self.left, self.right = value, left, right

def lca(root, a, b):
    if root is None or root.value in (a, b):
        return root
    left = lca(root.left, a, b)
    right = lca(root.right, a, b)
    if left and right:
        return root
    return left or right
Complexity: O(n) time and O(h) recursion depth for tree height h.
Edge cases: Clarify whether both target nodes are guaranteed to exist and whether values are unique.
Follow-up: How would parent pointers change the solution?
RUNNABLE PYTHON2026 SIGNAL

Streaming-median questions appear in current Apple MLE question lists and test heap fluency.

13. Streaming median

Problem: Support adding numbers one at a time and returning the median after each insertion.

Reasoning: Maintain a max-heap for the lower half and a min-heap for the upper half, keeping their sizes within one.

RUNNABLE PYTHON
import heapq

class MedianStream:
    def __init__(self):
        self.low = []   # negatives = max heap
        self.high = []
    def add(self, x):
        heapq.heappush(self.low, -x)
        heapq.heappush(self.high, -heapq.heappop(self.low))
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))
    def median(self):
        if not self.low:
            raise ValueError('empty stream')
        if len(self.low) > len(self.high):
            return -self.low[0]
        return (-self.low[0] + self.high[0]) / 2
Complexity: O(log n) per insertion and O(1) median lookup.
Edge cases: Empty stream, duplicate values, negative numbers, and numeric precision.
Follow-up: How would you compute an approximate median in a distributed stream?
RUNNABLE PYTHON2026 SIGNAL

Running top-k patterns are common in Meta-style coding and production streaming questions.

14. Top-k values from a stream

Problem: Keep the k largest values seen so far without storing the entire stream.

Reasoning: Maintain a min-heap of size k. Values below the heap minimum cannot belong to the current top k.

RUNNABLE PYTHON
import heapq

def top_k_stream(values, k):
    if k <= 0:
        return []
    heap = []
    for x in values:
        if len(heap) < k:
            heapq.heappush(heap, x)
        elif x > heap[0]:
            heapq.heapreplace(heap, x)
    return sorted(heap, reverse=True)

print(top_k_stream([9, 1, 4, 12, 3, 8], 3))
Complexity: O(n log k) time and O(k) space.
Edge cases: k greater than item count, duplicates, and whether distinct values are required.
Follow-up: Return the k most frequent items instead of largest values.
RUNNABLE PYTHON2026 SIGNAL

Graph traversal remains a standard algorithmic coding expectation in MLE loops, especially at Meta and Google.

15. Shortest path in an unweighted graph

Problem: Return the shortest number of edges from start to target.

Reasoning: Breadth-first search explores nodes in increasing distance from the start, so the first time the target is reached is optimal.

RUNNABLE PYTHON
from collections import deque

def shortest_path(graph, start, target):
    q = deque([(start, 0)])
    seen = {start}
    while q:
        node, dist = q.popleft()
        if node == target:
            return dist
        for nxt in graph.get(node, []):
            if nxt not in seen:
                seen.add(nxt)
                q.append((nxt, dist + 1))
    return None
Complexity: O(V+E) time and O(V) space.
Edge cases: Disconnected target, cycles, missing nodes, and directed versus undirected semantics.
Follow-up: What changes when edges have non-negative weights?
RUNNABLE PYTHON

1. Normalize a numeric list

Problem: Return min-max normalized values in [0,1]. Define behaviour when every value is equal.

Reasoning: Scan once for min and max, then transform. Equal values have zero range, so return zeros rather than divide by zero.

RUNNABLE PYTHON
def minmax(values):
    if not values:
        return []
    low, high = min(values), max(values)
    if low == high:
        return [0.0] * len(values)
    return [(x - low) / (high - low) for x in values]

print(minmax([2, 4, 6]))  # [0.0, 0.5, 1.0]
Complexity: O(n) time and O(n) output space.
Edge cases: Empty input, equal values, negative values, and non-finite floats need an explicit policy.
Follow-up: How would you fit min/max on training data and reuse them on validation data?
RUNNABLE PYTHON

2. Precision and recall from labels

Problem: Given binary truth and predictions, calculate precision and recall for positive label 1.

Reasoning: Count TP, FP, and FN in one pass. Define zero-denominator behaviour rather than crashing.

RUNNABLE PYTHON
def precision_recall(y_true, y_pred):
    if len(y_true) != len(y_pred):
        raise ValueError('length mismatch')
    tp = fp = fn = 0
    for truth, pred in zip(y_true, y_pred):
        tp += truth == 1 and pred == 1
        fp += truth == 0 and pred == 1
        fn += truth == 1 and pred == 0
    precision = tp / (tp + fp) if tp + fp else 0.0
    recall = tp / (tp + fn) if tp + fn else 0.0
    return precision, recall

print(precision_recall([1, 1, 0, 0], [1, 0, 1, 0]))
Complexity: O(n) time and O(1) auxiliary space.
Edge cases: Length mismatch, non-binary labels, no predicted positives, or no actual positives.
Follow-up: Add F1 and support multi-class macro averaging.
RUNNABLE PYTHON

3. Top-k frequent labels

Problem: Return the k most frequent labels, breaking ties alphabetically.

Reasoning: Build a frequency dictionary, then sort the distinct labels by negative count and label.

RUNNABLE PYTHON
from collections import Counter

def top_k(labels, k):
    if k < 0:
        raise ValueError('k must be non-negative')
    counts = Counter(labels)
    ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
    return ranked[:k]

print(top_k(['cat', 'dog', 'cat', 'bird', 'dog', 'cat'], 2))
Complexity: O(n + u log u) time for u unique labels and O(u) space.
Edge cases: k=0, k larger than unique labels, and unorderable mixed label types.
Follow-up: How would a heap change complexity when k is much smaller than u?
RUNNABLE PYTHON

4. Sliding-window moving average

Problem: Compute all means for a window of size k without summing every window again.

Reasoning: Maintain a running sum: add the new value and remove the value leaving the window.

RUNNABLE PYTHON
def moving_average(values, k):
    if k <= 0 or k > len(values):
        raise ValueError('invalid window')
    total = sum(values[:k])
    result = [total / k]
    for right in range(k, len(values)):
        total += values[right] - values[right - k]
        result.append(total / k)
    return result

print(moving_average([2, 4, 8, 10], 2))
Complexity: O(n) time and O(n−k+1) output space.
Edge cases: k=1, k=n, invalid k, and timestamp gaps if the requirement is time-based rather than row-based.
Follow-up: Adapt it to an iterator without storing all input.
RUNNABLE PYTHON

5. Group records by key

Problem: Group event dictionaries by user_id while preserving arrival order.

Reasoning: A dictionary of lists provides one-pass grouping and stable list order.

RUNNABLE PYTHON
from collections import defaultdict

def group_by(records, key):
    groups = defaultdict(list)
    for record in records:
        if key not in record:
            raise KeyError('missing ' + key)
        groups[record[key]].append(record)
    return dict(groups)

rows = [{'user_id': 2, 'event': 'open'}, {'user_id': 1, 'event': 'buy'}]
print(group_by(rows, 'user_id'))
Complexity: Expected O(n) time and O(n) space.
Edge cases: Missing keys, unhashable keys, and whether records should be copied or referenced.
Follow-up: Return only the latest event per user.
RUNNABLE PYTHON

6. Deduplicate events safely

Problem: Keep the first event for each event_id and report duplicate IDs.

Reasoning: A set gives expected O(1) membership. Preserve first-seen order by appending only unseen records.

RUNNABLE PYTHON
def deduplicate(events):
    seen, clean, duplicate_ids = set(), [], []
    for event in events:
        event_id = event['event_id']
        if event_id in seen:
            duplicate_ids.append(event_id)
            continue
        seen.add(event_id)
        clean.append(event)
    return clean, duplicate_ids

print(deduplicate([{'event_id': 'e1'}, {'event_id': 'e1'}, {'event_id': 'e2'}]))
Complexity: Expected O(n) time and O(u) space for unique IDs.
Edge cases: Missing or null IDs, conflicting duplicate payloads, and unbounded memory in streams.
Follow-up: How would you deduplicate within a seven-day streaming window?
RUNNABLE PYTHON

7. Mini-batch generator

Problem: Yield consecutive mini-batches without copying the entire dataset.

Reasoning: A generator produces one slice per iteration and naturally handles a smaller final batch.

RUNNABLE PYTHON
def batches(items, batch_size):
    if batch_size <= 0:
        raise ValueError('batch_size must be positive')
    for start in range(0, len(items), batch_size):
        yield items[start:start + batch_size]

for batch in batches(list(range(7)), 3):
    print(batch)
Complexity: O(n) total time and O(batch_size) per yielded list slice.
Edge cases: Empty input, invalid batch size, last partial batch, and whether shuffling is required.
Follow-up: How would you batch an iterator that has no len or slicing?
RUNNABLE PYTHON

8. Binary confusion matrix

Problem: Return TN, FP, FN, and TP and reject invalid labels.

Reasoning: Map each truth/prediction pair to one of four counters after validating values.

RUNNABLE PYTHON
def confusion_binary(y_true, y_pred):
    if len(y_true) != len(y_pred):
        raise ValueError('length mismatch')
    counts = {'tn': 0, 'fp': 0, 'fn': 0, 'tp': 0}
    for truth, pred in zip(y_true, y_pred):
        if truth not in (0, 1) or pred not in (0, 1):
            raise ValueError('labels must be 0 or 1')
        key = ('t' if truth == pred else 'f') + ('p' if pred else 'n')
        counts[key] += 1
    return counts

print(confusion_binary([1, 0, 1, 0], [1, 1, 0, 0]))
Complexity: O(n) time and O(1) auxiliary space.
Edge cases: Empty inputs, length mismatch, unexpected labels, and positive-label definition.
Follow-up: Generalize to a k×k multi-class matrix.
RUNNABLE PYTHON

9. Cosine similarity

Problem: Calculate cosine similarity for two equal-length vectors.

Reasoning: Compute dot product and both squared norms in one pass; zero vectors make the angle undefined.

RUNNABLE PYTHON
from math import sqrt

def cosine(a, b):
    if len(a) != len(b):
        raise ValueError('length mismatch')
    dot = sum(x * y for x, y in zip(a, b))
    norm_a = sqrt(sum(x * x for x in a))
    norm_b = sqrt(sum(y * y for y in b))
    if norm_a == 0 or norm_b == 0:
        raise ValueError('zero vector')
    return dot / (norm_a * norm_b)

print(round(cosine([1, 1], [1, 0]), 3))
Complexity: O(d) time and O(1) auxiliary space.
Edge cases: Zero vectors, length mismatch, floating-point precision, and large sparse vectors.
Follow-up: How would NumPy vectorization or normalization change repeated-search cost?

Use these links when an interview question exposes a gap. The interview guide focuses on explanation and decision-making; the linked lesson teaches the full concept.

Keep the answer honest: role boundaries, interview processes, and project outcomes vary. Never invent experience, impact, salary, or certainty to make an answer sound stronger.

Summary / Key Takeaways

  • Clarify input, output, constraints, and edge cases before coding.
  • Choose the simplest data structure that maintains the required invariant.
  • Lists preserve order, dictionaries count or group, and sets provide fast membership.
  • Sliding windows avoid repeated work by updating a maintained state.
  • Generators produce batches lazily and make memory behaviour explicit.
  • Evaluation code needs denominator, label, and shape policies rather than optimistic assumptions.
  • A complete coding answer includes verification, complexity, and a meaningful follow-up.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Python Coding for AI/ML Interviews"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5numerical/formula
What is the time complexity of one-pass moving average after the first window sum?
Question 2 of 5practical selection
Which structure best supports frequency counting?
Question 3 of 5application/scenario
What should cosine similarity do with a zero vector?
Question 4 of 5conceptual
Why use a generator for mini-batches?
Question 5 of 5debugging/diagnostic
A confusion-matrix function receives unequal label-array lengths. What is the cleanest response?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What is the time complexity of one-pass moving average after the first window sum?▼

Correct Answer: O(n)

Each value enters and leaves the maintained sum at most once, giving linear total time.

2Which structure best supports frequency counting?▼

Correct Answer: Dictionary/Counter

A dictionary maps each label to its count with expected constant-time updates.

3What should cosine similarity do with a zero vector?▼

Correct Answer: Raise or follow an explicit undefined-case policy

The cosine angle is undefined when either norm is zero, so the function needs an explicit contract.

4Why use a generator for mini-batches?▼

Correct Answer: It yields work lazily and bounds current memory

Generators produce one batch at a time rather than materializing all batches at once.

5A confusion-matrix function receives unequal label-array lengths. What is the cleanest response?▼

Correct Answer: Raise a clear validation error

Mismatched pairs make the metric undefined; explicit validation prevents a silent wrong result.

Keep moving through the path

Continue Learning

Free Download: Python for ML & AI Interviews

Solved Python interview problems for ML and AI roles with reasoning, code, dry runs, complexity, edge cases and practical data-processing patterns. Enter your email to download it instantly.

Next