How to solve a coding question out loud
- Restate and clarify: input type, duplicates, empty input, order matters?
- Say the simple approach and its cost (“a set makes lookups O(1)”).
- Write clean code with good names; small functions.
- Test with an example and edge cases out loud.
- Mention scale: “for a 50 GB file I'd stream it with a generator”.
Part 1: 15 coding problems (tested)
1. Remove duplicates, keep order
# 1. Remove duplicates but keep the original order
ids = [107, 101, 107, 103, 101, 108]
print(list(dict.fromkeys(ids))) # dicts keep insertion order (Python 3.7+)
print(sorted(set(ids))) # set() loses the order[107, 101, 103, 108] [101, 103, 107, 108]
2. Count values, top 2
# 2. Count how often each value appears; top 2
from collections import Counter
statuses = ["DELIVERED", "PLACED", "DELIVERED", "CANCELLED", "DELIVERED", "PLACED"]
print(Counter(statuses).most_common(2))[('DELIVERED', 3), ('PLACED', 2)]3. Merge two dicts
# 3. Merge two dicts (right side wins on conflicts)
defaults = {"retries": 3, "timeout": 10, "format": "csv"}
overrides = {"timeout": 30, "format": "parquet"}
print({**defaults, **overrides})
print(defaults | overrides) # Python 3.9+{'retries': 3, 'timeout': 30, 'format': 'parquet'}
{'retries': 3, 'timeout': 30, 'format': 'parquet'}4. Flatten nested JSON
# 4. Flatten a nested dict into dot-separated keys
def flatten(d, parent=""):
out = {}
for k, v in d.items():
key = f"{parent}.{k}" if parent else k
out.update(flatten(v, key) if isinstance(v, dict) else {key: v})
return out
print(flatten({"id": 1, "customer": {"name": "Asha", "address": {"city": "Kolkata"}}})){'id': 1, 'customer.name': 'Asha', 'customer.address.city': 'Kolkata'}5. Group records by key
# 5. Group records by a key
from collections import defaultdict
orders = [("Asha", 1999), ("Rahul", 4999), ("Asha", 1497), ("Priya", 4999)]
by_customer = defaultdict(list)
for name, amount in orders:
by_customer[name].append(amount)
print(dict(by_customer))
print({name: sum(a) for name, a in by_customer.items()}){'Asha': [1999, 1497], 'Rahul': [4999], 'Priya': [4999]}
{'Asha': 3496, 'Rahul': 4999, 'Priya': 4999}6. Chunk a stream into batches
# 6. Split a list into chunks of n (without loading everything at once)
def chunks(items, n):
batch = []
for item in items:
batch.append(item)
if len(batch) == n:
yield batch
batch = []
if batch:
yield batch
print(list(chunks(range(1, 8), 3)))[[1, 2, 3], [4, 5, 6], [7]]
7. Find missing ids
# 7. Find missing order ids in a sequence
received = [101, 102, 104, 105, 108]
print(sorted(set(range(min(received), max(received) + 1)) - set(received)))[103, 106, 107]
8. Second-largest distinct value (no sorting)
# 8. Second-largest DISTINCT value without sorting
def second_largest(nums):
first = second = None
for n in set(nums):
if first is None or n > first:
first, second = n, first
elif second is None or n > second:
second = n
return second
print(second_largest([1999, 4999, 4999, 1497, 299]))1999
9. Top N by value
# 9. Top 3 products by revenue
import heapq
revenue = {"Headphones": 9995, "Smartwatch": 24995, "Charger": 3493, "Laptop Stand": 3897, "Phone Case": 2990}
print(heapq.nlargest(3, revenue.items(), key=lambda kv: kv[1]))[('Smartwatch', 24995), ('Headphones', 9995), ('Laptop Stand', 3897)]10. Group anagrams
# 10. Group words that are anagrams (classic string/dict question)
words = ["listen", "silent", "enlist", "google", "gogole", "cat"]
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w)
print(list(groups.values()))[['listen', 'silent', 'enlist'], ['google', 'gogole'], ['cat']]
11. is vs ==
# 11. is vs ==
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b, a is b) # equal values, different objects
print(a is a, None is None)True False True True
12. The lambda-in-a-loop trap
# 12. The late-binding trap with lambdas in a loop
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # all see the final i
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs]) # default argument captures each value[2, 2, 2] [0, 1, 2]
13. Sort by several keys
# 13. Sort by several keys: status A→Z, then amount high→low
rows = [("PLACED", 299), ("DELIVERED", 1999), ("DELIVERED", 4999), ("PLACED", 1196)]
print(sorted(rows, key=lambda r: (r[0], -r[1])))[('DELIVERED', 4999), ('DELIVERED', 1999), ('PLACED', 1196), ('PLACED', 299)]14. A decorator that counts calls
# 14. A decorator that counts calls
import functools
def count_calls(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
wrapper.calls += 1
return fn(*args, **kwargs)
wrapper.calls = 0
return wrapper
@count_calls
def load_batch(n):
return n
for i in range(4):
load_batch(i)
print(load_batch.calls)4
15. Max of a huge file without loading it
# 15. Largest order in a huge file without loading it
import csv
with open("data/orders.csv", newline="") as f:
best = max(
(r for r in csv.DictReader(f) if r["quantity"].isdigit()),
key=lambda r: int(r["quantity"]) * int(r["price"]),
)
print(best["order_id"], best["product"])102 Smartwatch
Part 2: 35 concept questions
🎯 Core Python
Try to answer out loud first, then tap to check.
Q1List vs tuple vs set vs dict?Fresher+
Q2Mutable vs immutable types?Fresher+
Q3What does 'is' compare?Fresher+
Q4What are *args and **kwargs?Fresher+
Q5What is a list comprehension?Fresher+
Q6Explain the mutable default argument bug.1–3 yrs+
Q7How are arguments passed?1–3 yrs+
Q8What is if __name__ == '__main__' for?1–3 yrs+
Q9Shallow vs deep copy?1–3 yrs+
Q10Time complexity of list append, list 'in', dict lookup?1–3 yrs+
🎯 Functions, generators and OOP
Try to answer out loud first, then tap to check.
Q1What is a generator and why use it?1–3 yrs+
Q2What is a decorator?1–3 yrs+
Q3What is a context manager?1–3 yrs+
Q4What is a closure?1–3 yrs+
Q5What are dataclasses?1–3 yrs+
Q6Explain inheritance vs composition.3+ yrs+
Q7What are @staticmethod and @classmethod?3+ yrs+
🎯 Files, errors and APIs
Try to answer out loud first, then tap to check.
Q1Why use 'with open'?Fresher+
Q2How do you process a 50 GB file?1–3 yrs+
Q3JSON vs JSON Lines?1–3 yrs+
Q4How do you handle bad records?1–3 yrs+
Q5When should you retry?1–3 yrs+
Q6How do you paginate an API?1–3 yrs+
Q7How do you keep secrets out of code?3+ yrs+
🎯 pandas, databases and performance
Try to answer out loud first, then tap to check.
Q1How do you handle missing values in pandas?1–3 yrs+
Q2merge vs concat?1–3 yrs+
Q3Why Parquet over CSV?1–3 yrs+
Q4How do you prevent SQL injection?1–3 yrs+
Q5Fastest bulk load into PostgreSQL?1–3 yrs+
Q6What is the GIL?3+ yrs+
Q7Threads vs processes vs asyncio?3+ yrs+
Q8pandas vs PySpark?3+ yrs+
Q9How would you speed up a slow Python transformation?3+ yrs+
Q10How do you make a Python pipeline idempotent?3+ yrs+
Q11What would you put in a pipeline's CI?3+ yrs+
Python for data engineers: cheat sheet
# Files
from pathlib import Path; import csv, json
with open(path, newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f))
data = json.loads(Path("x.json").read_text())
for line in open("events.jsonl"): event = json.loads(line)
# Collections
from collections import Counter, defaultdict
totals = defaultdict(float); counts = Counter(statuses).most_common(3)
unique_in_order = list(dict.fromkeys(items))
merged = defaults | overrides
# Robustness
try: value = int(raw)
except ValueError: rejected.append(row)
log = logging.getLogger(__name__); log.info("loaded %d rows", n)
# APIs
r = requests.get(url, params={"page": p}, headers=auth, timeout=10); r.raise_for_status()
# pandas
df = pd.read_csv(p); df["q"] = pd.to_numeric(df["q"], errors="coerce")
df.drop_duplicates().dropna(subset=["id"]).merge(dim, on="id", how="left").to_parquet("out.parquet")
# Databases
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
conn.execute("INSERT ... VALUES (%s, %s) ON CONFLICT (id) DO UPDATE ...", (a, b))
# Advanced
def gen(path): yield from csv.DictReader(open(path))
@functools.wraps(fn) # inside every decorator
@dataclass(frozen=True)
class Order: order_id: int; amount: floatKey takeaways
- ✓Most Python interview problems are dicts, sets and generators in disguise.
- ✓Always talk about edge cases and scale.
- ✓Explain your approach before coding.
- ✓Revisit the linked lesson for any answer that surprised you.
Frequently asked questions
What Python questions do data engineer interviews ask?
Core data structures and their complexity, string and dict manipulation, generators, decorators, error handling, file processing at scale, pandas operations, and small coding problems like de-duplication, grouping, flattening JSON and chunking.
Do I need LeetCode-hard algorithms?
Usually not for data engineering. Expect practical problems: process records, group and count, handle big files, clean messy data. Know Big-O for lists, dicts and sets.
How should I practise?
Re-solve every problem on this page without looking, then vary it (top 3 instead of top 1, nested lists inside the JSON). Explain your approach out loud and mention edge cases: empty input, None, duplicates, huge files.
Should I use pandas in a coding interview?
Only if allowed. Many interviews want plain Python to see your fundamentals; mention how you'd do it in pandas or SQL as a bonus.
🧠 Quick check: Python interview
1. Remove duplicates but keep order:
2. [lambda: i for i in range(3)] — calling each returns...
3. Average lookup cost in a dict:
4. Threads in CPython help most with...
Checking your access…