Problems that mirror real engineering tasks. These require combining multiple skills: parsing, state machines, operator precedence, and building useful tools from scratch.
Real-world problems are hard because they're ambiguous.
In an interview, clarify edge cases before coding: What if the input is empty? What about duplicates? Malformed lines?
These three problems are examples of "build a small tool" questions that companies actually ask.
P 53Coding ProblemMedium
Requirements Conflict Finder
Given multiple requirements.txt-style strings, find packages that appear with conflicting version pins.
Each line is like requests==2.28.0 or flask>=2.0. Lines starting with # are comments.
A conflict is when the same package name appears with different version specifiers across the files.
Return a dict of {package_name: set_of_conflicting_specs}.
Example
req1 = "requests==2.28.0\nflask>=2.0\n# comment"
req2 = "requests==2.30.0\nflask>=2.0\nnumpy==1.24"
find_conflicts(req1, req2)
→ {"requests": {"==2.28.0", "==2.30.0"}}
# flask appears with the same spec in both — not a conflict
# numpy only in req2 — not a conflict
str.splitlines()str.startswith for commentsstr.partition for operator splitdefaultdict(set)filter by len(set) > 1
Solution
from collections import defaultdict
from typing import Dict, Set
# Version operators in order from most specific to least
VERSION_OPS = ["~=", "==", "!=", ">=", "<=", ">", "<"]
deffind_conflicts(*req_files: str) -> Dict[str, Set[str]]:
# package_name -> set of version specifiers seen
packages: dict = defaultdict(set)
for req_text in req_files:
for line in req_text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continuefor op in VERSION_OPS:
if op in line:
pkg, _, ver = line.partition(op)
packages[pkg.strip()].add(f"{op}{ver.strip()}")
breakelse:
# No operator found — bare package name, ignore version
packages[line].add("*")
# Only return packages with multiple different specifiers (conflicts)return {pkg: specs for pkg, specs in packages.items() iflen(specs) > 1}
Key ideas: Try each operator in order from longest to shortest — checking ">=" before ">" prevents partial matches.
str.partition(op) splits on the first occurrence and always returns exactly 3 parts — safer than split.
Using a set per package means the same spec in two files counts once (not a conflict).
The for...else construct: the else runs only if the loop completed without a break — used to catch bare package names.
P 54Coding ProblemMedium
Directory Tree Builder
Given a list of file paths like ["src/app/main.py", "src/app/utils.py", "src/tests/test_main.py"],
build a nested dict representing the directory tree.
Then implement a print_tree(tree) function that displays it like the Unix tree command.
split('/') on pathsnested defaultdictrecursive tree buildingrecursive pretty-printto_dict conversion
Solution
from collections import defaultdict
from typing import List, Dict
defbuild_tree(paths: List[str]) -> Dict:
# A tree factory: each node is a defaultdict of the same type
tree = lambda: defaultdict(tree)
root = tree()
for path in paths:
parts = path.split("/")
node = root
for part in parts:
node = node[part] # auto-creates nested nodesdefto_dict(d) -> dict:
return {k: to_dict(v) for k, v in d.items()}
returnto_dict(root)
defprint_tree(tree: dict, indent: int = 0) -> None:
for name insorted(tree.keys()):
print(" " * indent + name)
if tree[name]: # non-empty dict = directoryprint_tree(tree[name], indent + 1)
Key insight:lambda: defaultdict(tree) creates a self-referential factory — each new node is itself a defaultdict that creates more nodes on access.
This lets you do root["src"]["app"]["main.py"] without any pre-initialisation.
Convert to a plain dict at the end so the result is JSON-serialisable.
The print_tree recursion is clean: files have an empty dict ({}) and directories have a non-empty one — so if tree[name] distinguishes them.
P 55Coding ProblemHard
Arithmetic Expression Evaluator
Evaluate an arithmetic expression string like "3 + 5 * 2 - 8 / 4"
without using eval(). Support +, -, *, / (integer division),
integers, and spaces. Respect operator precedence (* and / before + and -).
stack-based evaluationtokenisationoperator precedence with stackapply_op helper
Solution
defevaluate(expression: str) -> int:
# Operator precedence: * and / are higher than + and -
precedence = {"+": 1, "-": 1, "*": 2, "/": 2}
defapply_op(ops: list, vals: list) -> None:
op = ops.pop()
b, a = vals.pop(), vals.pop()
if op == "+": vals.append(a + b)
elif op == "-": vals.append(a - b)
elif op == "*": vals.append(a * b)
elif op == "/": vals.append(int(a / b)) # truncate toward zero
ops: list = []
vals: list = []
for token in expression.split():
if token.lstrip("-").isdigit():
vals.append(int(token))
elif token in precedence:
# Evaluate any pending ops with higher or equal precedence firstwhile (ops and ops[-1] in precedence
and precedence[ops[-1]] >= precedence[token]):
apply_op(ops, vals)
ops.append(token)
# Apply remaining operatorswhile ops:
apply_op(ops, vals)
return vals[0]
Two-stack algorithm (Dijkstra's shunting-yard):
Maintain two stacks — vals for numbers and ops for operators.
When you see an operator, evaluate any pending operators in ops that have higher or equal precedence before pushing the new one.
This ensures * and / are applied before + and -.
At the end, drain the remaining operators.
To support parentheses: push "(" to ops and on ")", evaluate until you pop the matching "(".
All 50 Problems Complete!
You've worked through log parsing, strings, dict patterns, sequences, nested JSON, data structures, classic algorithms, and real-world tools. That covers the full spectrum of Python interview coding. Add more categories any time.