A worked example: folder sizes that stay right
An Airbnb software engineer candidate reported a tree whose leaves hold numbers and whose every other node holds the sum of its children, where values change and any node can be read in between (1 report). Here it is as disk usage.
The prompt: you get (item, folder) pairs and the size in bytes of each file. Support resize(file, size), and size_of(node): the bytes in a file, or in a folder and everything under it.
PAIRS = [("docs", "/"), ("photos", "/"), ("cv.pdf", "docs"), ("notes.txt", "docs"),
("beach.jpg", "photos"), ("2024", "photos"), ("trip.jpg", "2024")]
SIZES = {"cv.pdf": 120, "notes.txt": 4, "beach.jpg": 2300, "trip.jpg": 1800}
print(len(PAIRS), "pairs,", len(SIZES), "file sizes")
7 pairs, 4 file sizes
1. Clarify. Those answers pick the design:
- Is
resizegiven the new size or the change? The new size, here. - Can a folder hold bytes of its own? Say no, but make the code not care.
- How many reads against changes, and how deep can it go? Reads far outnumber changes, and folders can nest thousands deep.
2. The obvious version. Store each file's size, and on every read walk the node's subtree with a stack and add up. A change is . A read is , where is the size of the subtree, so reading the top is every time. Here it is as a method of SizeTree, the class this worked example builds, which keeps each node's own bytes in self.own and its children in self.children:
def size_by_walking(self, node):
total, stack = 0, [node]
while stack:
item = stack.pop()
total += self.own[item]
stack.extend(self.children[item])
return total