Indentation-Aware Code Folding Engine
Data Structure DesignModel answerLast updated
Build a class that collapses and restores indentation-defined code blocks, tracking nested fold state and remapping display line numbers after each operation.
Background
Text editors like VS Code let you fold away blocks of code — clicking a triangle next to a function header hides its body until you unfold it. Your job is to build the data structure behind that feature.
Initialization
Your editor is created with a flat list of source-code lines. Block structure is entirely determined by leading-space indentation, the way Python works:
- Every line's indentation is a multiple of 4 spaces.
- A line
His a block header when the line directly following it is indented more deeply thanH. - The body of header
His the unbroken sequence of lines afterHthat are all indented more deeply thanH. The body ends at the first line whose indentation is no greater thanH's, or at the end of the file. - Bodies can contain their own headers, creating nested folds.
Displaying the buffer
Implement a render() method that returns the list of currently visible lines, one entry per visible line, in this format:
<display_number> <marker><original line text>
display_numbercounts visible lines from 1; hidden lines are skipped entirely and do not occupy a number.markeris+(plus then a space) for any block header, and the empty string for every other line.- The original line text includes its leading spaces.
Fold operations
Both operations below take a display number — the number shown in the most recent render() output, not a position in the original file.
shrink(d) — Fold the block whose header is currently shown at display number d. The header line stays visible; every line in its body is hidden. If d does not point to a header, or that header's block is already folded, do nothing.
expand(d) — Unfold the block whose header is currently shown at display number d. Lines that were hidden solely because of this fold become visible again. However, any line that is hidden because a nested header inside this block was previously folded remains hidden — each header tracks its own fold state independently.
A line is visible if and only if it is not contained in the body of any currently-folded header.
Example
Editor initialized with these five lines (4-space indent shown explicitly):
a = 1
for i in range(10):
print(i)
print(i ** 2)
b = 10
render() returns:
1 a = 1
2 + for i in range(10):
3 print(i)
4 print(i ** 2)
5 b = 10
After shrink(2), render() returns:
1 a = 1
2 + for i in range(10):
3 b = 10
The two body lines are hidden and b = 10 is renumbered to display 3. Calling expand(2) after that restores the original five-line output.
What to implement
class CodeEditor:
def __init__(self, lines: list[str]): ...
def shrink(self, d: int) -> None: ...
def expand(self, d: int) -> None: ...
def render(self) -> list[str]: ...
Constraints
- 1 ≤ number of lines ≤ 10⁴; each line is at most 200 characters.
- Indentation is spaces only, always a multiple of 4. The first line has indentation 0. No line is indented more than 4 spaces deeper than the one before it.
- At most 10⁴ total calls across
shrink,expand, andrender. - The display number passed to
shrinkorexpandis always valid for the most recentrender()output.
Hints
Hint 1
Separate what never changes (block structure) from what changes on every fold (the collapsed/expanded flag per header). Compute each header's block-end index once at construction time using a monotonic stack — the same "next smaller or equal element" pattern used in problems like daily temperatures.
Hint 2
To enumerate visible lines you don't need a hidden flag on every line. A single forward scan is enough: emit the current line, then if it is collapsed jump directly to its block-end index (skipping the whole body in O(1)), otherwise advance by one. Nested collapsed headers inside an expanded block are encountered naturally and trigger their own jumps.
Hint 3
Display numbers are relative to the current visible list and become stale after every fold. Never cache a mapping from original file index to display number across calls. Instead, resolve display number d by taking the (d−1)-th element of the list produced by the visibility scan on each operation.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to split the problem cleanly into two layers:
- Static structure — computed once in
__init__, never mutated: each line's indentation depth, whether it is a block header, and the index of the first line after its block (end[i]). - Dynamic state — a single boolean array
collapsed[i], one entry per line.
With that split, every operation reduces to a linear scan over visible lines.
Computing block ends with a monotonic stack
The block of line i ends at the first later line j with indent[j] <= indent[i]. That is the classic "next smaller-or-equal element" problem.
Walk forward through all lines. Before pushing index j, pop every index on the stack whose indentation is greater than or equal to indent[j] and record their end as j. Anything left on the stack at the end gets end = n. Each index is pushed and popped at most once, so this runs in O(n).
A line is a header if and only if the line immediately after it has strictly greater indentation: indent[i+1] > indent[i].
Visibility scan
To list the visible lines in order, do a single forward walk:
- Start at index 0.
- Emit the current index as visible.
- If
collapsed[i]isTrue, jump toend[i](skips the whole body in O(1)). - Otherwise advance to
i + 1.
This naturally handles nesting. An expanded outer block is walked line by line; when the scan hits a collapsed inner header it jumps over that inner body. A collapsed outer block is jumped over entirely — inner collapsed headers are skipped but their collapsed flags are untouched, so they restore correctly when the outer block is later expanded. No extra bookkeeping needed.
Display-number resolution
Display numbers are positions in the current visible list, which changes after every fold. Resolve d by calling the visibility scan and taking element at index d - 1. Never store a stale mapping from original index to display number.
Complexity
__init__: O(n) time and space.- Each call to
shrink,expand, orrender: O(V) where V ≤ n is the number of lines the scan visits. Collapsed regions are skipped in O(1), so heavily folded files are fast in practice. - Worst case: 10⁴ calls × 10⁴ lines = 10⁸ simple iterations.
renderhas to output O(V) strings anyway, so the scan is not the bottleneck.
Follow-up: O(log n) per operation. Keep a segment tree or Fenwick tree that counts "how many collapsed ancestors cover this line." Folding a block is a range increment; unfolding is a range decrement. Finding the d-th line with a zero count takes O(log n) by binary lifting. Worth mentioning if asked, but the linear scan is the expected answer in a screen.
Edge cases
- Nested collapse, then outer expand. Shrink the inner header, shrink the outer header, expand the outer header. The inner block stays hidden — its
collapsedflag isTrueand was never touched by the outer expand. The scan will hit the inner header after the outer expand, see it is collapsed, and jump over it. - Repeated
shrinkon an already-collapsed header: settingTruetwice is harmless. expandon a non-header or already-expanded line: the flag is alreadyFalse; setting it again is a no-op.- Single-line file: no headers, no folding possible.
render()returns["1 <line>"]. - Header with a one-line body: folds and unfolds correctly;
end[i] == i + 2. - Last line: can never be a header because there is no following line to be more deeply indented.
- Line content in output: preserve original leading spaces. The
+marker is inserted between the display number and the content; it does not replace indentation.
Python implementation
class CodeEditor:
def __init__(self, lines: list[str]):
self.lines = list(lines)
n = len(self.lines)
# Indentation depth of each line
self.indent = [len(s) - len(s.lstrip(' ')) for s in self.lines]
# end[i] = first index j > i where indent[j] <= indent[i], or n
self.end = [n] * n
stack: list[int] = []
for j in range(n):
while stack and self.indent[stack[-1]] >= self.indent[j]:
self.end[stack.pop()] = j
stack.append(j)
# remaining entries already default to n
# A line is a header iff the next line is strictly deeper
self.is_header = [
i + 1 < n and self.indent[i + 1] > self.indent[i]
for i in range(n)
]
self.collapsed = [False] * n
def _visible(self) -> list[int]:
"""Return original indices of all currently visible lines."""
out: list[int] = []
i, n = 0, len(self.lines)
while i < n:
out.append(i)
if self.collapsed[i]:
i = self.end[i] # jump over the folded body
else:
i += 1
return out
def shrink(self, d: int) -> None:
idx = self._visible()[d - 1]
if self.is_header[idx]:
self.collapsed[idx] = True # no-op if already True
def expand(self, d: int) -> None:
idx = self._visible()[d - 1]
if self.collapsed[idx]:
self.collapsed[idx] = False
def render(self) -> list[str]:
result = []
for display_num, idx in enumerate(self._visible(), start=1):
marker = "+ " if self.is_header[idx] else ""
result.append(f"{display_num} {marker}{self.lines[idx]}")
return result
What separates strong answers
- Keeping structure and state separate. Candidates who mutate the line list directly (deleting and re-inserting lines) almost always break the nested-expand behavior or end up with O(n) mutations per fold.
- One-pass block-end computation. Recomputing block ends by re-scanning per header is O(n²) on deeply nested input; the monotonic stack brings it to O(n).
- Re-resolving display numbers on every call. Caching a display→original mapping across operations is a common bug: the mapping is invalidated the moment any fold changes.
- Nested collapse correctness unprompted. The scan-and-jump approach handles it automatically; explicitly storing a "hidden" flag per line usually gets this wrong.