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.
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.
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
The interview coding contract
Say this before and after implementation
15 solved interview exercises
Current big-tech coding patterns are shown first, followed by the core AI/data exercises.
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.
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]))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.
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('{[()]}'))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.
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 rightStreaming-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.
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]) / 2Running 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.
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))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.
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 None1. 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.
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]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.
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]))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.
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))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.
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))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.
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'))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.
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'}]))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.
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)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.
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]))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.
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))Review the deeper lessons
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.