HRT Python-Track Interview Questions, Answered: Dicts, the GIL, Memory, OS and Debugging
HRT's Python-track interviews ask how Python works, not just whether you can write it. This guide takes every Python and systems question from 19 reports and answers each one the way you would say it in the room.
Coverage: Hudson River Trading, Python-track software roles (new grad, junior, senior, Python Developer, Ops Dev) · questions reported 2021–2026 · answers written by FastPrep and checked on CPython 3.12
How to use this guide
We collected 19 interview reports for HRT's Python-track roles. They are summarized in the two-part series Part 1 and Part 2. Twelve of those 19 candidates were asked about Python itself. On 2026-11-09 we added more first-hand reports, including the first ones that describe the new grad Python phone rounds. The series lists the questions. This guide answers them.
Section 0 shows the new grad Python loop as far as reports go, from 2021 to 2026. No one has posted a new grad onsite on the Python track itself, so the onsite rows come from new grads on the C++ track or whose language wasn't stated. The loop is otherwise the same. The rest of the guide uses Python-track reports from every level, because the questions repeat across levels.
Every section has the same parts:
- What they asked. The question as candidates described it, in our words, and how many reports had it.
- Say this. A short answer you could give out loud in about a minute.
- One level deeper. What to say when the interviewer pushes.
- Try it. A few lines of Python you can run to see it for yourself. Outputs are from CPython 3.12 on a 64-bit Mac. Some numbers change between versions.
| Topic | Reports that had it | Section |
|---|---|---|
| The new grad Python loop, round by round | 9 new grad reports | 0 |
| How a dict works, hash collisions, resizing | 6 | 1 |
dict subclass bugs, hashable classes, lists as keys |
3 | 2 |
| How CPython manages memory and garbage collection | 2 (plus a garbage-collector question at a 2025 onsite) | 3 |
| The GIL, pros and cons | 1 | 4 |
How with and context managers work |
6 | 5 |
Generators and yield |
8 | 6 |
Decorators, *args and **kwargs |
3 | 7 |
| How the interpreter and compilation work | 1 | 8 |
| OS basics and Linux commands | 7 | 9 |
| C and C++ knowledge questions | 4 | 10 |
| The cost of growing an array | 2 | 11 |
| Reading and debugging code, often over SSH | 7 | 12 |
The last section lists the practice problems built from these reports.
0. The new grad Python loop, from the reports
| Stage | What candidates described | Reported by |
|---|---|---|
| OA | An online assessment comes before any interview. In 2021 two Python new grads got the same two problems: remove adjacent AB or CD pairs, and the longest path in an a/b-labelled tree with no two equal letters in a row. | 2021 new grads ×2, 2023 and 2026 new grads |
| Phone 1, 2022 (about 45 minutes) | Knowledge and code reading: what yield does and iterators vs generators, what with does, how a dict is built, threads vs processes, Python threads vs OS threads. Another candidate read and improved small functions using yield and with, checked a stock-price function for correctness and speed, and found the bug in a dict subclass. |
2022 new grads ×2 |
| Phone 1, 2023 (about 1 hour) | Two parts. First, quick code reading: say what a snippet does, what's wrong with it and how to improve it. Generators, context managers and __setitem__ came up. Second, SSH into a machine, read the error in a log file, fix the code or the data, then check the fix. |
2023 new grad, Python |
| Phone 1, 2026 (about 30 minutes) | One timed coding task: a ball moves through a grid maze, and tilt events change its direction. The candidate said it was the same task a 2026 C++ new grad got. | 2026 new grad, Python |
| Phone 2 | The recruiter listed operating systems, algorithms, data structures and Python internals. In 2026 the recruiter also said Python candidates get some C questions. No one posted the actual questions. | 2023 new grad, 2026 new grad |
| Onsite (new grad, language not stated) | One 75-minute object-oriented coding problem with many small rules, plus short reaction and planning games. The candidate passed. | 2026 new grad |
| Onsite (new grad, C++ track, 2021) | One report: a debugging-style talk, a hard algorithm, a stream reader built on a fixed 4096-byte read call, and a team lead round (mmap vs read for a huge file, a slow network, why HRT). Another: two hours filling in a class's functions and optimizing them, then system design. |
2021 new grads ×2 |
What to take from this:
- Read the rules twice before you code. On the maze task, one 2026 candidate wrote a fast, clean solution and still failed, because they assumed one kind of cell could be walked through. Another said the explanation took about 10 minutes, which left about 15 to code.
- Expect to read and fix code, not only write it. New grad and senior Python reports both describe being shown code, asked what it prints, then asked to fix it, sometimes over SSH. Section 12 covers this.
- Expect one long class problem at the onsite. Every new grad onsite report from 2021 to 2026 had one long round of implementing a class with many small rules, then making it faster.
- Know the internals. Sections 1 to 10 cover the Python, OS and C questions.
Practice: Tilting Maze Ball (phone screen) and Tiered Expiring Item Store (onsite).
1. How does a Python dict work?
What they asked. "How does a Python dict work under the hood?" came up in six reports: 2021, a 2022 new grad phone screen, 2024, a final round reported in 2025, and a 2026 knowledge round that asked about collision resolution by name. A 2021 phone screen asked the general version: collisions, the cost of each operation, when a hash table resizes, and what resizing costs.
Say this
A dict is a hash table. To store a key, Python calls hash(key) and uses the low bits of that number to pick a slot in a table. It stores the key, the value and the hash in that slot.
To look a key up, Python hashes it again and goes to the same slot. It first compares the stored hash, then checks the key with ==.
If two keys want the same slot, that's a collision. Python doesn't keep a list in each slot. Instead it tries another slot, then another, in a fixed order, until it finds the key or an empty slot. This is called open addressing.
The table is never allowed to get more than about two-thirds full. When it would, Python makes a bigger table and puts every key in again.
Lookup, insert and delete are O(1) on average. In the worst case, when many keys collide, they are O(n).
One level deeper
The next slot isn't just "the next one over." Python computes the next slot from the current slot and the parts of the hash it hasn't used yet. So two keys that clash once usually split up on the next try. Simply walking to the neighbor slot would make keys pile up in clumps.
There are really two arrays. Since Python 3.6 a dict keeps:
- a small index table, which is the hash table itself. Each slot holds just a number: where the entry lives in the second array.
- a dense entries array, which holds (hash, key, value) in the order you inserted them.
d = {"apple": 1, "kiwi": 2, "fig": 3}
index table (8 slots) entries array (insertion order)
slot 0: empty 0: hash("apple"), "apple", 1
slot 1: 2 ------------> 1: hash("kiwi"), "kiwi", 2
slot 2: empty 2: hash("fig"), "fig", 3
slot 3: 0 ------------>
slot 4: empty
slot 5: 1 ------------>
slot 6: empty
slot 7: empty
(The slot numbers here are made up. Real ones depend on the hashes.)
This layout saves memory, because the big rows are packed together and only the small index table has empty space. It is also why dicts keep insertion order. That order became a language guarantee in Python 3.7.
Deleting leaves a marker. When you delete a key, its slot isn't simply emptied. It gets a "deleted" marker. If it were emptied, a lookup for another key that had collided past this slot would stop early and wrongly say "not found." The markers are cleaned up the next time the table is rebuilt.
Resizing. When an insert would push the table past two-thirds full, Python allocates a new table. Its size is a power of two, about three times the number of keys. Then every entry is inserted again. That one insert costs O(n). But because the table grows by a big factor each time, the total cost over n inserts is still O(n). So each insert is O(1) on average. This is called amortized O(1).
Deleting doesn't give memory back. A dict doesn't shrink when you delete keys. The memory comes back only when a later insert triggers a rebuild, or when you copy the dict.
The hash rules.
- If
a == b, thenhash(a)must equalhash(b). Otherwise a dict could hold two "equal" keys. - So
1,1.0andTrueare the same key. - Mutable built-ins like
listanddicthave no hash. If you define__eq__on a class and don't define__hash__, Python sets__hash__toNoneand the class becomes unhashable. - String hashes are randomized each time Python starts (see
PYTHONHASHSEED). This stops attackers from sending many keys that all collide, which would make a server's dicts slow. hash(-1)is-2. In CPython's C code, -1 means "an error happened," so no object is allowed to hash to -1.
Try it
import sys
d = {}
last = sys.getsizeof(d)
for i in range(30):
d[i] = i
if sys.getsizeof(d) != last:
print(f"key {len(d)}: {last} -> {sys.getsizeof(d)} bytes")
last = sys.getsizeof(d)
# key 1: 64 -> 224 bytes (first table: 8 slots, room for 5 keys)
# key 6: 224 -> 352 bytes (16 slots, room for 10)
# key 11: 352 -> 632 bytes (32 slots, room for 21)
# key 22: 632 -> 1168 bytes (64 slots)
print({1: "int", 1.0: "float", True: "bool"})
# {1: 'bool'} one key: the first key object is kept, the last value wins
print(hash(-1), hash(-2))
# -2 -2
big = {i: i for i in range(1000)}
before = sys.getsizeof(big)
for i in range(999):
del big[i]
print("before:", before, "after:", sys.getsizeof(big))
# before: 36952 after: 36952 deleting didn't shrink it
Follow-ups to expect (our guess, based on what was asked):
- Why two-thirds and not full? Near full, collisions get much more frequent and each lookup tries many slots.
- What makes a dict slow? A bad
__hash__. If every key returns the same hash, every lookup walks through all of them. - How is a
setdifferent? Same idea, but it stores only keys, and it doesn't keep insertion order.
2. Dict subclasses, hashable classes and list keys
What they asked. In a 2024 interview over SSH, the candidate was shown a class that subclasses dict and asked to find the bug that causes an error. A 2022 new grad got the same kind of question and said you need to know how __setitem__ behaves. Neither report shared the code. Below are the classic bugs that fit, so you'll recognize whichever one you get. A 2026 knowledge round asked two related questions: how do you make a class hashable, and can a list be a dict key?
Say this
Subclassing dict and overriding __setitem__ or __getitem__ doesn't do what most people expect. The built-in methods are written in C, and they don't call your overrides. dict.__init__, update() and setdefault() skip your __setitem__. get() skips your __getitem__. So your rule works for d[k] = v and silently doesn't work for the others.
The fix is to subclass collections.UserDict instead. Its methods are written in Python and go through __setitem__ and __getitem__. The other fix is to override every method that writes or reads.
Try it
class LowerKeys(dict):
def __setitem__(self, key, value):
super().__setitem__(key.lower(), value)
d = LowerKeys(A=1) # __init__ skips the override
d["B"] = 2 # uses the override
d.update(C=3) # skips it
d.setdefault("D", 4) # skips it
print(d)
# {'A': 1, 'b': 2, 'C': 3, 'D': 4}
from collections import UserDict
class LowerKeys2(UserDict):
def __setitem__(self, key, value):
super().__setitem__(key.lower(), value)
d2 = LowerKeys2(A=1)
d2["B"] = 2
d2.update(C=3)
d2.setdefault("D", 4)
print(d2.data)
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}
The read side has the same trap:
class LowerGet(dict):
def __getitem__(self, key):
return super().__getitem__(key.lower())
g = LowerGet(a=1)
print(g["A"], g.get("A"))
# 1 None
One level deeper
__missing__is the supported hook. If adictsubclass defines__missing__, thend[key]calls it when the key isn't there. It does not add the key, andget()andindon't use it.collections.defaultdictis built on this.- Defining
__eq__breaks hashing. If the subclass, or a key class, defines__eq__without__hash__, its objects become unhashable. Putting one in a set or using it as a key raisesTypeError: unhashable type. - A mutable key. If a key's hash depends on fields that change after insertion, the dict looks in the wrong slot and can't find it anymore.
Making a class hashable, and why a list can't be a key
Say this. A dict needs two things from a key. Equal keys must have equal hashes, and a key's hash must not change while it's in the dict. To make your own class hashable, define __eq__ and __hash__, and build both from the same fields. Those fields shouldn't change after the object is made. The easy way is @dataclass(frozen=True), which writes both methods and blocks changes.
A list can't be a dict key. A list can change, so its hash could change after you insert it. Python sets list.__hash__ to None for that reason. Use a tuple instead. A tuple is hashable only if everything inside it is hashable.
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
print({Point(1, 2): "a"}[Point(1, 2)])
# a two equal Points find the same entry
try:
{[1, 2]: "x"}
except TypeError as e:
print(e)
# unhashable type: 'list'
print({(1, 2): "ok"}[(1, 2)])
# ok a tuple works
@dataclass
class Mutable:
x: int
try:
hash(Mutable(1))
except TypeError as e:
print(e)
# unhashable type: 'Mutable' a plain dataclass defines __eq__, so __hash__ becomes None
3. How does CPython manage memory?
What they asked. A 2025 final round had a whole interview on CPython internals, including memory management. A 2026 knowledge round asked how Python's garbage collection works. Separately, at an onsite reported in 2025 (the talk there was in C++ terms), two interviewers asked how to implement a garbage collector. They pushed back when the candidate's answer was built on reference counting.
Say this
CPython uses two things together.
Reference counting. Every object keeps a count of how many references point to it. Assigning it to a name, putting it in a list or passing it to a function adds one. When a reference goes away, the count drops by one. When the count hits zero, the object is freed right away. This is simple and frees memory at a predictable moment.
A cycle collector. Reference counting alone can't free a cycle. If A points to B and B points to A, both counts stay at 1 even when nothing else can reach them. So CPython also runs a garbage collector, found in the gc module. It looks only at container objects, like lists, dicts and class instances, and finds groups that are only reachable from each other. It frees those groups.
del x doesn't free anything by itself. It removes one name, and that lowers the count by one.
One level deeper
- Generations. Most objects die young. So the collector checks new objects often and old objects rarely. On Python 3.12,
gc.get_threshold()gives(700, 10, 10): three generations, with a young collection after roughly 700 more allocations than deallocations. The exact scheme has changed in newer versions, so check it on the version you use. - Small objects use pymalloc. Objects of 512 bytes or less come from Python's own allocator. It grabs big blocks from the OS and splits them up, which is faster than calling
mallocfor every small object. A side effect: a Python process often doesn't shrink after it frees many objects, because a big block goes back to the OS only when all of it is free. - Some objects are shared. The integers -5 to 256 are created once and reused, and many strings that look like names are "interned." That's why
issometimes works on small numbers and then fails on bigger ones. Use==for values. - Saving memory.
__slots__removes the per-instance__dict__.weakreflets you point to an object without keeping it alive, which helps with caches and parent pointers.
If they ask you to implement a GC (the 2025 onsite question), describe mark-and-sweep:
- Start from the roots: globals, the stack, registers.
- Follow every pointer and mark every object you can reach.
- Sweep through all objects and free the ones that aren't marked.
Then compare it with reference counting. Mark-and-sweep handles cycles but has to pause to scan. Reference counting frees objects right away but can't free cycles and costs a little on every assignment. CPython uses both for exactly this reason. We built this as a practice problem: Design a Mark-and-Sweep Garbage Collector.
Try it
import gc, sys
x = []
print(sys.getrefcount(x))
# 2 (x, plus the temporary reference from passing it to getrefcount)
class Node:
pass
gc.collect()
a, b = Node(), Node()
a.other, b.other = b, a # a cycle
del a, b # counts stay at 1, so nothing is freed yet
print(gc.collect())
# 2 the cycle collector found and freed the two Node objects
print(gc.get_threshold())
# (700, 10, 10)
n1, n2 = 256, int("256")
m1, m2 = 257, int("257")
print(n1 is n2, m1 is m2)
# True False
4. How does the GIL work? What are the pros and cons?
What they asked. A 2021 Python Developer phone screen asked how the GIL works, with its pros and cons.
Say this
The GIL, or Global Interpreter Lock, is one lock per interpreter. A thread must hold it to run Python bytecode. So in a normal CPython build, only one thread runs Python code at a time, even on a machine with many cores.
A thread lets go of the GIL when it waits on I/O, like reading a file or a socket. It also lets go every 5 milliseconds by default, so other threads get a turn. Many C extensions, NumPy for example, release the GIL while they do heavy work.
Pros:
- Reference counts don't need their own locks, so single-threaded code stays fast.
- C extensions are easier to write safely.
- The interpreter itself is simpler.
Cons:
- CPU-heavy Python code doesn't get faster with more threads.
So the rule of thumb is: use threads or asyncio for I/O-heavy work. Use multiprocessing for CPU-heavy work, because each process has its own interpreter and its own GIL. Or move the heavy part into C code that releases the GIL.
One level deeper
The GIL doesn't make your code thread-safe. It protects the interpreter's own data, not yours. n += 1 is several bytecode steps. A thread switch can happen between them, and then an update is lost. You still need a threading.Lock.
import dis
def bump():
global n
n += 1
dis.dis(bump)
# LOAD_GLOBAL n
# LOAD_CONST 1
# BINARY_OP (+=)
# STORE_GLOBAL n
# (output trimmed)
If thread A loads n, then thread B loads the same n, both store n + 1. One increment is lost.
The GIL is becoming optional. Python 3.13 added an experimental "free-threaded" build without the GIL (PEP 703). In Python 3.14 that build is officially supported, but it's still a separate build and not the default. To make it work, CPython had to change how reference counting works. Mentioning this shows you're current.
import sys
print(sys.getswitchinterval())
# 0.005 (5 ms)
5. How does with work?
What they asked. A 2024 Singapore phone screen did a deep dive on Python basics, including "how does with work?" Context managers came up again in 2022 and 2023 new grad phone screens and a 2025 senior Python phone screen, as code to read and fix, and in a 2021 Python Core Developer phone screen.
Say this
with uses the context manager protocol. The object after with must have two methods:
__enter__runs at the start. Its return value is whatasbinds to.__exit__runs at the end, always. It runs on a normal finish, onreturn, and when an exception is raised.
__exit__ gets three arguments: the exception type, the exception value and the traceback. If there was no exception, all three are None. If __exit__ returns something truthy, the exception is swallowed. Otherwise it keeps going up.
It's a cleaner way to write try/finally, so the cleanup can't be forgotten. Files, locks and database transactions all use it.
Try it
class Timer:
def __enter__(self):
print("enter")
return self # this is what "as t" gets
def __exit__(self, exc_type, exc, tb):
print("exit, exception:", exc_type)
return False # don't swallow exceptions
with Timer() as t:
print("body")
# enter
# body
# exit, exception: None
Roughly, with Timer() as t: body turns into this:
manager = Timer()
t = manager.__enter__()
try:
... # body
except BaseException as e:
if not manager.__exit__(type(e), e, e.__traceback__):
raise
else:
manager.__exit__(None, None, None)
One level deeper
- If
__enter__raises,__exit__never runs. Thewithblock was never entered. contextlib.contextmanagerturns a generator into a context manager. Code beforeyieldis the enter part. Code after it is the exit part. Wrap theyieldintry/finallyif cleanup must happen even on errors.
from contextlib import contextmanager
@contextmanager
def opened(path):
f = open(path)
try:
yield f
finally:
f.close()
- A lock in a
withis released even if the body raises. That's the main reason to usewith lock:instead of callingacquire()andrelease()yourself.
6. What does yield do?
What they asked. A 2021 Python Developer phone screen asked what yield is for. Generators came up in seven more reports: 2022 and 2023 new grad phone screens and a 2025 senior phone screen as code to read, a 2022 new grad round on iterators vs generators, a 2022 intern round, a 2021 Python Core Developer phone screen, and a 2026 knowledge round that asked what a generator is.
Say this
A function that contains yield is a generator function. Calling it doesn't run its body. It returns a generator object.
Each time you call next() on that object, the body runs until it reaches a yield. The yielded value is handed back, and the function pauses there. Its local variables and its place in the code are saved. The next next() picks up right after that yield. When the function ends, the generator raises StopIteration, and a for loop treats that as the end.
The point is laziness: values are made one at a time, when asked for. So you can walk through a huge file or an endless sequence without holding it all in memory.
Try it
def count_up(limit):
print("start")
i = 0
while i < limit:
yield i
i += 1
print("done")
g = count_up(2) # prints nothing yet
print(next(g)) # start, then 0
print(next(g)) # 1
print(list(g)) # done, then []
def lines(path):
with open(path) as f:
for line in f:
yield line.rstrip("\n")
# Only one line is in memory at a time, however big the file is.
One level deeper
- A generator expression,
(x * x for x in data), is a short generator.[x * x for x in data]builds the whole list right away. send(value)resumes the generator and makes the pausedyieldexpression evaluate tovalue. This is how two-way coroutines used to be written.yield from otherhands off to another generator until it's done. Thereturnvalue of a generator is carried insideStopIteration.value.- A generator can be used only once. After it's exhausted, looping over it again gives nothing.
- Generators and
asyncio.async/awaitgrew out of generators. Both pause a function and resume it later. An event loop resumes coroutines when their I/O is ready. If you get the "design something like asyncio" question from the intern report, this is the place to start: Design an asyncio-Style Event Loop.
7. Decorators, *args and **kwargs
What they asked. A 2026 Python and Linux round asked to explain decorators and what * and ** mean. A 2025 senior Python phone screen showed decorator code, asked what it prints, then asked for fixes or missing pieces.
Say this
A decorator is a function that takes a function and returns a new one, usually a wrapper around the original. Writing @timed above a def is short for add = timed(add). It runs once, when the function is defined. You use decorators to add timing, logging, caching or checks without touching the function's body.
The wrapper takes *args, **kwargs, so it accepts any arguments and passes them on. Wrap it with functools.wraps, so the new function keeps the original's name and docstring.
* and ** do two jobs.
- In a definition,
*argscollects extra positional arguments into a tuple, and**kwargscollects extra keyword arguments into a dict. - In a call,
*spreads a list or tuple into positional arguments, and**spreads a dict into keyword arguments.
* also works when unpacking: first, *rest = items.
Try it
import functools, time
def timed(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter() - start:.4f}s")
return result
return wrapper
@timed
def add(a, b):
return a + b
print(add(2, 3), add.__name__)
# add took 0.0000s (the time varies)
# 5 add wraps kept the name
def repeat(n): # a decorator that takes an argument
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return [func(*args, **kwargs) for _ in range(n)]
return wrapper
return decorator
@repeat(3)
def hi():
return "hi"
print(hi())
# ['hi', 'hi', 'hi']
def show(*args, **kwargs):
print(args, kwargs)
show(1, 2, x=3)
# (1, 2) {'x': 3}
nums, opts = [1, 2], {"x": 3}
show(*nums, **opts)
# (1, 2) {'x': 3}
first, *rest = [1, 2, 3, 4]
print(first, rest)
# 1 [2, 3, 4]
One level deeper
- A decorator with arguments is a function that returns a decorator, so there are three layers, like
repeatabove. - Decorators stack. The one closest to the
defis applied first. - Without
functools.wraps,add.__name__would be"wrapper". That confuses logs, debuggers and other decorators. - Built-in decorators you should know:
@property,@staticmethod,@classmethodand@functools.lru_cache. - A class can be a decorator if it defines
__call__.
8. How do the interpreter and compilation work?
What they asked. A 2024 Singapore first round asked deep Python questions, some about how compilation and the interpreter handle code.
Say this
Python is compiled, then interpreted. When you run a file, CPython does this:
- Tokenize and parse the source into a syntax tree, called an AST.
- Compile the tree into bytecode. Bytecode is a list of simple instructions like "load this variable" or "add the top two values." Each function gets its own code object.
- Cache the bytecode of imported modules as
.pycfiles in__pycache__, so the next import can skip steps 1 and 2 if the source hasn't changed. - Run the bytecode in a loop in C, the evaluation loop. It's a stack machine: instructions push values onto a stack and pop them off.
The compiler does a few small optimizations. For example, it works out math on constants ahead of time. It doesn't do the big optimizations a C compiler does.
Try it
import dis
dis.dis(compile("x = 24 * 60 * 60", "<demo>", "exec"))
# LOAD_CONST 0 (86400) the math was done at compile time
# STORE_NAME 0 (x)
# (output trimmed)
One level deeper
- Local variables are fast. Globals are slower. Locals sit in a fixed array and are read with
LOAD_FAST. Globals and built-ins are looked up in dicts withLOAD_GLOBAL. That's why moving work into a function, or binding a global to a local name in a hot loop, can speed code up. - Python 3.11 made the interpreter adaptive. After an instruction runs a few times, it's swapped for a version specialized to the types it actually saw. For example, an add that keeps seeing two ints. This is a big reason 3.11 was much faster than 3.10.
- Python 3.13 added an experimental JIT compiler. It's off by default.
- "Is Python compiled or interpreted?" Both. It's compiled to bytecode, and the bytecode is interpreted. Saying exactly that, with the steps above, is a strong answer.
9. Operating system basics: memory, processes and Linux
What they asked.
- A 2021 phone screen asked how the OS gives memory to processes, virtual vs physical memory, and what happens when virtual memory is bigger than physical memory. It also asked about stack vs heap.
- A 2024 phone screen asked basic Linux questions.
- A 2022 report with a two-day final asked how you can run many processes on one computer.
- A 2026 Python and Linux round asked about swap, threads vs processes, symlinks vs hard links and several shell tasks. A 2025 senior Python phone screen also asked threads vs processes.
The 2026 new grad was told their second round covers operating systems and "how computers work". A 2023 new grad's recruiter listed operating systems too. So expect this part.
Virtual vs physical memory: say this
Every process gets its own virtual address space. It looks like one big, private range of memory. The OS and the CPU's memory management unit translate each virtual address to a real place in RAM, using a page table. Memory is handled in fixed-size pages, usually 4 KB.
This gives two things:
- Isolation. One process can't read another's memory.
- Flexibility. A page gets real RAM only when the process first touches it.
When virtual memory is bigger than physical memory: that's normal. Most of a process's virtual space is never touched, so it never needs RAM. If processes really do touch more than the RAM, the OS moves pages that haven't been used lately out to disk, called swap, and brings them back on a page fault. That works, but disk is far slower than RAM. If it happens a lot, the machine spends its time moving pages and almost stops. That's called thrashing. On Linux, if there's no swap left, the out-of-memory killer ends a process.
Stack vs heap: say this
- The stack holds function calls: their local variables and where to return to. Each thread has its own. It grows and shrinks as functions are called and return, so it's very fast. But it's small and fixed in size. Recursion that goes too deep runs off the end: a stack overflow.
- The heap holds memory you ask for at runtime and that must outlive one function call, like
mallocin C ornewin C++. It's bigger and more flexible, but slower to allocate, and someone has to free it.
In CPython, every Python object lives on the heap. The interpreter still uses the C stack itself. That's one reason Python has a recursion limit: sys.getrecursionlimit() is 1000 by default.
Many processes on one computer: say this
The OS scheduler shares the CPU cores. Each process runs for a short time slice. Then the OS saves its state, including registers and which page table it uses, and loads another process's state. That's a context switch. With several cores, several processes really run at the same moment. Virtual memory keeps them from touching each other's memory.
Threads are different. Threads in one process share the same memory, so they can talk cheaply. But they need locks. Processes don't share memory by default, so they talk through pipes, sockets or shared memory that they set up on purpose. On Linux, a new process is usually made with fork(), which copies the parent cheaply by sharing pages until one side writes. Then exec() loads a new program.
Linux command questions
The 2026 round asked a batch of these. Replies to that report suggested the role leaned toward DevOps, so a pure SWE loop may ask fewer. Short answers:
| Question | Short answer |
|---|---|
| How do you check memory on a host? | free -h for totals, top or htop per process, /proc/meminfo for detail, and vmstat 1 to watch swapping as it happens. |
| Which command shows the current directory? | pwd. |
How do you list files without ls? |
echo * (the shell expands the pattern; hidden files are skipped), printf '%s\n' *, find . -maxdepth 1, or python3 -c "import os; print(os.listdir())". |
| What is swap, and why use it? | Disk space the OS uses as overflow for RAM pages. It keeps the machine running under memory pressure, but it's far slower than RAM. |
| Thread vs process? | Threads share one address space. Each process has its own. See above. |
| Symlink vs hard link? | A hard link is another name for the same file (the same inode). The data stays until the last name is removed. It can't cross file systems or point to a directory. A symlink is a small file that stores a path. It can cross file systems, and it breaks if the target moves or is deleted. |
How do you delete a file named -rf? |
rm -- -rf or rm ./-rf. The -- tells rm that options are over. The ./ makes the name stop starting with a dash. |
You ran rm -rf by mistake. Can you get the files back? |
Usually not with a command. Linux has no trash, and rm removes the names; the space is marked free and can be overwritten at any moment. Real recovery comes from backups, snapshots or version control. Stop writing to that disk at once. If a running program still has a file open, you can copy it back from /proc/<pid>/fd/. Undelete tools work only sometimes. |
10. C and C++ knowledge questions
What they asked. The 2026 new grad was told by the recruiter that Python-track candidates get questions in C, to test low-level reasoning. No Python candidate has posted their C questions yet. Three C and C++ knowledge rounds at HRT were posted, and they show the style:
- A 2026 phone screen for a low-level C++ role: stack vs heap. How to find which way the stack grows on an unknown machine, and why comparing two locals in one function doesn't work.
inline: what it buys and what it costs. Whatnewdoes compared withmalloc. Placementnew, and when it helps performance. Pointers vs references. What happens in a segmentation fault. Then two-sum, the K smallest elements, and why quickselect is O(n) on average. - A 2023 second-round phone screen: fill in code that prints a string, basic vector operations, and itoa (turn an int into a string).
- A 2022 core dev intern who applied for Python but was interviewed in C++: threads vs processes and why thread switches are cheaper, ways processes talk to each other, building a deque (then a circular one), building a vector and choosing its growth factor. In round 2: read a file through a fixed 4096-byte read call, and a rate limiter, with follow-ups on profiling and scaling.
Short answers to the reported questions
- Which way does the stack grow? Call a second function, then compare the address of a local in the caller with a local in the callee. The callee's frame is newer, so the difference tells you the direction. Two locals in one function don't work, because the compiler may place them in any order or keep one in a register.
inline. It asks the compiler to paste the function's body at the call site. That saves the call and lets the compiler optimize across it. Too much of it makes the program bigger, which can hurt the instruction cache. In C++,inlinealso allows the same definition to appear in many files.newvsmalloc.malloc(n)returns n raw bytes, orNULLif it fails.new Tgets memory for aT, runs its constructor and returns a typed pointer. If it fails, it throwsstd::bad_alloc. Free each with its partner:freeordelete.- Placement
new.new (buffer) T(...)builds an object in memory you already own, without allocating. Memory pools and containers use it. In latency-critical code it lets you allocate everything up front and keepmallocout of the hot path. You must call the destructor yourself. - Pointer vs reference. A pointer is an address. It can be null and can be pointed somewhere else. A reference is another name for an existing object. It must be set when it's created and can't be pointed elsewhere.
- Segmentation fault. The program touched an address its process may not use: not mapped, or mapped without that permission. The hardware raises a fault, the kernel finds no valid mapping, and it sends
SIGSEGV, which ends the program by default. Common causes: null or dangling pointers, running past the end of an array, and stack overflow. - itoa. Handle zero and negative numbers. Build digits from the right with
% 10and/ 10, then reverse them. Watch the most negative int: negating it overflows, so work with negative remainders or a wider type. - Quickselect. Partition around a pivot, then recurse into one side only. With a random pivot, each round shrinks the work by a constant fraction on average. So the total is about n + n/2 + n/4 + ..., which is O(n). Bad pivots every time give O(n²).
Connecting Python to C
These links help when an interviewer asks how Python works underneath:
- A Python object is a C struct. Every object starts with a reference count and a pointer to its type. That's why even a small int takes 28 bytes on a 64-bit build, while a C
inttakes 4. - A Python list is an array of pointers. Each slot is 8 bytes and points to an object somewhere else on the heap. That's why a list of a million floats uses far more memory than a C
double[], and whyarrayor NumPy store raw numbers instead. - Pointers and memory. Know
mallocandfree, what a dangling pointer is, what a memory leak is, and why reading past the end of an array is undefined behavior in C but raisesIndexErrorin Python. - Sizes and bits. Know how ints are stored in two's complement, what overflow means in C, and why Python ints never overflow (they grow as needed).
import sys
print(sys.getsizeof(1), sys.getsizeof(2**64))
# 28 36 a Python int is an object, and big ints grow
Good practice, taken from the reported questions: write itoa, a growable array with a chosen growth factor, a deque, and a reader built on a fixed-size read call. Do them by hand in C or C++.
11. The cost of growing an array
What they asked. At an onsite reported in 2025, an interviewer said C++ std::vector::push_back is O(1). The candidate argued that one push can trigger a full copy, which matters for real-time code. A 2021 phone screen asked the same thing about hash tables: when do they resize, and what does it cost? A 2022 intern candidate was asked to build a vector and choose its growth factor.
Say this
Both answers are right, and saying both is the strong answer.
push_back, or Python's list.append, is amortized O(1). When the array is full, it allocates a bigger one and copies everything over. That single call is O(n). But the array grows by a constant factor each time, so copies get rarer as it grows. The total work for n appends is O(n), so it's O(1) on average.
Choosing the growth factor. A bigger factor, like 2, means fewer copies but more unused space. A smaller one, like 1.5, wastes less and lets the allocator reuse freed blocks. CPython's list grows by about 12.5% plus a few slots, because lists are small and very common.
If one slow call is a problem, as in latency-sensitive trading code, you reserve the space up front. In C++ that's reserve(n). In Python it's [None] * n, or a preallocated NumPy array. Then no append in the hot path ever copies.
Try it
import sys
items = []
last = sys.getsizeof(items)
grew_at = []
for i in range(40):
items.append(i)
if sys.getsizeof(items) != last:
grew_at.append(len(items))
last = sys.getsizeof(items)
print(grew_at)
# [1, 5, 9, 17, 25, 33] Python over-allocates, so most appends don't copy
12. Reading and debugging code over SSH, and "why did my script get slower?"
What they asked. This is HRT's most distinctive round for Python candidates. Seven reports describe reading, explaining or debugging code:
- In 2023, a new grad Python phone screen had two parts. First, quick code reading: what does this do, what's wrong, how would you improve it. Second, SSH into a machine, read the error in a log file, and fix the code or the data.
- In 2025, a senior Python phone screen showed code using decorators, generators, context managers, threads and processes. It asked what the code prints, then asked for fixes or missing pieces. A later part used SSH for simple file navigation.
- In 2022 (London Ops Dev, offer accepted), a phone round had five Python scripts, each with a CSV file. They were run over SSH. Bugs were in the data, the code or both. The onsite had another debugging round, plus a question: a Python script got slower while its code didn't change; what could cause that, and how would you fix it?
- In 2024, a round over SSH and a shared
tmuxterminal asked the candidate to explain Python snippets and find bugs, with one interviewer and two observers. - In 2024, a round asked what a piece of code does and how to improve it, plus Bash.
- In 2025, a senior candidate had two 1-hour interviews mixing technical questions, live coding and debugging.
- In 2026, a senior OA asked the candidate to fix a program so its output matched the requirement.
How to work through a debugging task
- Look at the data before the code. Run
head,wc -landtailon the file. Check for a header row, the delimiter, blank lines at the end, Windows line endings (\r\n), quotes around fields, and odd values. - Run the script and read the whole traceback. The last line says what went wrong. The lines above say where.
- Talk while you work. In these rounds the interviewer is watching how you search, not only whether you find it.
- Make the smallest fix. Then rerun to prove it.
Bugs that often show up in Python CSV scripts:
- The header row is treated as data.
- Numbers are compared as strings:
"10" < "9"isTrue. - Money is summed as
floatand comes out a cent off. Usedecimalor integer cents. - A trailing empty line breaks a
split(","). - A dict keyed by name loses rows when two rows share a name.
- An off-by-one in a range or slice.
You can practice exactly this format here: Debug Python Scripts and Their CSV Files.
"The script got slower, but the code didn't change": say this
First I'd measure, not guess. I'd time it, then profile it with cProfile or py-spy to see where the time goes. Then I'd check these, in roughly this order:
- The input grew. A step that is O(n²) is fine at a thousand rows and painful at a million. Common causes:
x in some_listinside a loop, building a string with+=in a loop, or a nested loop join. Fix: use a set or dict, use"".join, or sort and merge. - The environment changed. The disk is full or slow. A network service or database it calls got slower. The machine is short on memory and swapping. Other processes compete for the CPU. Check with
top,df,freeand timing on each external call. - Something other than "the code" changed. A library or Python version was upgraded. A config value changed. A cache it relied on is now cold, or got turned off.
- The data's shape changed. For example, more duplicate keys, much longer strings, or one huge row.
Pick the fix from what you measured. If the input grew, fix the algorithm. If the machine is the problem, fix the machine or move the work. Don't rewrite code that isn't the cause.
Practice problems from these reports
All 15 come from reports in the series.
Debugging and design
- Debug Python Scripts and Their CSV Files (Python Ops Dev phone screen and onsite)
- Design a Mark-and-Sweep Garbage Collector (onsite)
- Design an asyncio-Style Event Loop (intern phone screen)
- Design a Hit Counter with Disk-Backed Payloads (onsite)
- Design Packet Routing Between a Hub and Node Servers (final round)
Coding
- Polydivisible Pandigital Numbers (interview)
- Collapse Equal Adjacent Pairs (Python Developer OA)
- Maximum Sum of a k-Node Downward Path (Python Developer OA)
- Fewest Flips to Split a Binary String into Blocks (Python SWE OA)
- Fewest Increments to Make Every Value Unique (Python Developer OA)
- Most Value from At Most Two Projects (Python Developer OA)
- Contact Tracing Through Timed Meetings (intern phone screen)
From the new grad and onsite reports added on 2026-11-09
- Tilting Maze Ball (new grad phone screen, 2026)
- Tiered Expiring Item Store (new grad onsite, 2026)
- Read a File from Distributed Chunks (onsite, 2026)
One-page review
| Question | The short answer |
|---|---|
| How does a dict work? | A hash table with open addressing. Hash picks a slot. Collisions try other slots. Kept under two-thirds full. O(1) average. |
| Why do dicts keep order? | Entries sit in a dense array in insertion order. The hash table only stores indexes into it. |
| What does resizing cost? | O(n) for that one insert, amortized O(1), because the size grows by a big factor. |
What's wrong with subclassing dict? |
C methods like update, get and __init__ skip your overrides. Use UserDict. |
| How do you make a class hashable? | Define __eq__ and __hash__ from the same fields that never change, or use @dataclass(frozen=True). |
| Can a list be a dict key? | No. It can change, so it has no hash. Use a tuple. |
| How is memory freed? | Reference counting frees most objects at once. A cycle collector frees reference cycles. |
| What is the GIL? | One lock, so one thread runs bytecode at a time. Released on I/O and every 5 ms. Threads for I/O, processes for CPU. |
Does the GIL make n += 1 safe? |
No. It's several bytecode steps. Use a lock. |
How does with work? |
__enter__ at the start. __exit__ always at the end, with exception info. Truthy return swallows the exception. |
What does yield do? |
Makes a generator. Pauses and resumes with state saved. Values are made lazily. |
| What is a decorator? | A function that takes a function and returns a wrapped one. @d means f = d(f). Use functools.wraps. |
What do * and ** mean? |
In a definition they collect extra arguments into a tuple and a dict. In a call they spread a sequence or a dict into arguments. |
| How is Python run? | Source, then AST, then bytecode (cached as .pyc), then a stack-based evaluation loop. |
| Virtual vs physical memory? | Private address space per process, mapped to RAM by page tables. Pages get RAM when touched and swap to disk under pressure. |
| Stack vs heap? | Stack: per-thread function frames, fast, small. Heap: runtime allocations, flexible, must be freed. |
| Symlink vs hard link? | Hard link: another name for the same inode. Symlink: a file that stores a path and can break. |
Delete a file named -rf? |
rm -- -rf or rm ./-rf. |
Is push_back O(1)? |
Amortized O(1). A single call can copy everything. Reserve ahead in latency-critical code. |
| Script got slower, same code? | Measure first. Then check input growth, environment, dependencies and data shape. |
Related: HRT Python track, Part 1 · Part 2 · New grad Python track, 9 reports
Sources: Anywhere useful interview info can be found.
Comments
0No comments yet — be the first to share what you know.