Allocate Contiguous Free Block Runs With a Segment Tree
Last updated: November 29, 2026
Quick Overview
Design a free-space allocator over n blocks that supports allocate(k), returning the lowest starting block of k contiguous free blocks (or -1) and marking them used, and free(start, k), both in O(log n).
Netapp
November 29, 20260
0
0 solved
Design a free-space allocator over n blocks that supports allocate(k), returning the lowest starting block of k contiguous free blocks (or -1) and marking them used, and free(start, k), both in O(log n).
A write-anywhere file system like WAFL wants to lay out each consistency point's writes in long contiguous runs to keep RAID stripes full, so the allocator's ability to find free runs quickly matters for write performance. Interviewers on file system teams use this to see whether you can go past a linear bitmap scan to a tree that summarizes runs, and get the merge logic right.
What the Interviewer Expects
- Explains why a linear bitmap scan is O(n) per allocation and too slow at scale
- Stores prefix, suffix and best free-run lengths per segment tree node
- Merges children correctly, including runs that span the midpoint
- Uses lazy propagation for range assign on allocate and free
- Finds the leftmost fit by preferring left child, then the crossing run, then right child
- Validates against a brute-force allocator
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you allocate 'best fit' (smallest run that fits) instead of first fit?
- The block space is 4 billion blocks. How do you reduce memory, for example by working on bitmap words at the leaves?
- How does a write-anywhere file system avoid fragmentation over years of snapshots that pin old blocks?
- How would you make allocation concurrent across multiple CPU cores?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Blocks 0..n-1, all free initially. allocate(k) returns the lowest start s such that s..s+k-1 are free, marks them used, or returns -1. free(start, k) marks a run free (assume it was allocated). Bo...
High-Level Design
Each segment tree node keeps three numbers for its range: pre (free run touching its left edge), suf (free run touching its right edge) and best (longest free run inside). Combining children: `p...