Header-Preserving Markdown Chunker
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Write a function split_markdown(markdown: str, max_size: int) -> list[str] that partitions a Markdown string into a sequence of text chunks in document order while keeping every chunk's length within max_size characters.
A line is recognized as a Markdown heading of level k (1 <= k <= 6) if and only if it begins at column 0 with k consecutive # characters followed immediately by an ASCII space (' '), such as # Overview (level 1) or ### Endpoints (level 3). Lines without that exact prefix—for instance #tag, ##, ####### Deep, or lines with leading spaces before #—are treated as ordinary body lines belonging to whichever headings are currently open.
As you scan from top to bottom, headings form a nested hierarchy:
- Encountering a heading of level k closes every currently active heading whose level is greater than or equal to k, while keeping active ancestor headings with levels strictly less than k.
- Headings may skip levels (for example, ### Subtopic directly beneath # Chapter).
Chunking and whitespace rules:
1. Split markdown on "\n". Ignore empty or whitespace-only lines (line.strip() == ""), returning [] if no non-blank lines exist. Preserve every non-blank line's exact characters, including indentation and trailing spaces.
2. Join lines within a chunk using "\n", with no leading or trailing newline on the chunk string.
3. Pack lines greedily in original order: append the next non-blank line to the current chunk whenever the joined chunk length remains <= max_size.
4. Whenever a line cannot fit in the current chunk (or starts the very first chunk), emit the current chunk if non-empty and begin a new chunk by prepending all active ancestor headings (from outermost to innermost) before that line. Prepended heading lines and "\n" separators count toward max_size. (If a heading line itself begins a new chunk, only its strictly shallower active ancestors are prepended; the heading is not duplicated.)
Examples
Example 1
Input:
markdown = "# Guide\n## Setup\nInstall SDK\nSet API key"
max_size = 30
Output:
[
"# Guide\n## Setup\nInstall SDK",
"# Guide\n## Setup\nSet API key"
]
Explanation: "# Guide\n## Setup\nInstall SDK" has 28 characters (<= 30). Appending "\nSet API key" (12 more characters) would bring the length to 40 > 30, so a second chunk starts mid-section and repeats both active headings ("# Guide" and "## Setup") above "Set API key" (28 characters total).
Example 2
Input:
markdown = "# Manual\n## Auth\n### OAuth\ntoken flow\n\n## Billing\ninvoices"
max_size = 37
Output:
[
"# Manual\n## Auth\n### OAuth\ntoken flow",
"# Manual\n## Billing\ninvoices"
]
Explanation: The first four lines join to exactly 37 characters. The blank line is skipped. When "## Billing" (level 2) arrives, it closes both "### OAuth" (level 3) and "## Auth" (level 2), leaving only "# Manual" as its parent. Because 37 + 1 + 10 = 48 > 37, Chunk 1 closes and Chunk 2 opens with "# Manual\n## Billing", followed by "invoices" (28 characters total).
Example 3
Input:
markdown = "#note\nfirst item\nsecond item"
max_size = 18
Output:
[
"#note\nfirst item",
"second item"
]
Explanation: "#note" has no space after #, so it is treated as normal body text rather than a heading. "#note\nfirst item" uses 16 characters (<= 18), and "second item" starts a second chunk with no prepended headings.
Constraints
0 <= len(markdown) <= 10^51 <= max_size <= 10^5- Every individual non-blank line together with its active ancestor headings fits within
max_size(if an oversized line ever appears, place it intact with its ancestor headings into its own chunk rather than slicing mid-line).
Step-by-step walkthrough
Understand the goal and whitespace rules
We want to partition a Markdown string into an ordered list of text chunks so that every chunk stays within
max_sizecharacters. Whenever a new chunk opens partway through a section, we prepend the active ancestor headings above its first line so the chunk retains its full section context.We follow four clean line and packing rules:
- Line splitting: Split the input on
"\n". Join lines inside each chunk with a single"\n", with no leading or trailing newline on a chunk. - Blank lines: Drop empty or whitespace-only lines (
line.strip() == ""), so chunks never waste budget on blank separators and an empty document returns[]. - Exact line text: Preserve every non-blank line verbatim, including indentation and trailing spaces.
- Greedy packing: Keep appending lines to the current chunk while they fit (
<= max_size), and open a new chunk only when appending the next line would overflow (if a single oversized line ever exceedsmax_size, emit it intact in its own chunk rather than slicing mid-line).
- Line splitting: Split the input on
Detect valid Markdown headers
By the problem's definition, a line is a header only if it begins with 1 to 6
#characters immediately followed by a single space' '.Why check carefully instead of testing
line.startswith("#")? Because everyday text contains lookalikes that are plain content, not headers:"# Title" -> level 1 header (1 '#' + space) "###### Deep" -> level 6 header (6 '#' + space) "#hashtag" -> level 0 content (no space after '#') "##" -> level 0 content (nothing after '#') "####### Seven" -> level 0 content (7 '#' is too many) " # Indented" -> level 0 content (starts with a space, not '#')We count consecutive
#characters from index0, then check both the1..6range and the space right after them:def get_header_level(line: str) -> int: """Return 1..6 if `line` starts with 1..6 '#' characters followed by ' ', else 0.""" hash_count = 0 while hash_count < len(line) and line[hash_count] == "#": hash_count += 1 # A valid Markdown header needs 1 to 6 leading '#' characters AND a space right after. if 1 <= hash_count <= 6 and hash_count < len(line) and line[hash_count] == " ": return hash_count return 0Track open sections with a stack
As we read from top to bottom, a new header closes any open section at the same level or deeper (larger level number), while leaving shallower parent headers open. For example, seeing
## D(level 2) finishes### C(level 3) and## B(level 2), while keeping# A(level 1).A stack (a list where we push and pop from the end) models this naturally. We store
(level, header_line)pairs from outermost to innermost:Line read Pop condition (top >= level) Stack after update --------- ---------------------------- ------------------------------------ # A nothing to pop [(1, "# A")] ## B top is 1 (< 2), keep [(1, "# A"), (2, "## B")] ### C top is 2 (< 3), keep [(1, "# A"), (2, "## B"), (3, "### C")] ## D pop (3, "### C"), (2, "## B") [(1, "# A"), (2, "## D")]Notice a crucial timing detail when
lineitself is a header like## D: - If## Dstarts a new chunk, its parent context is[(1, "# A")]— not the old## B, and not## Dtwice! - Therefore, we pop closed headers (>= level) before placinglineinto a chunk, and we push(level, line)onto the stack after placinglineinto the chunk.Because header levels on the stack strictly increase from bottom to top, the stack holds at most 6 items at any time, and skipped levels (such as
# Adirectly to### C) work automatically without special cases.Pack chunks greedily in O(1) per line
Suppose
current_linesholds the lines of the chunk we are building. Checking whetherlinefits by building"\n".join(current_lines + [line])on every step would re-copy the entire chunk each time. Instead, we maintaincurrent_length, the exact length of"\n".join(current_lines).When
current_linesis non-empty, appendinglineadds one"\n"separator pluslen(line)characters, so the new size would becurrent_length + 1 + len(line):- Fits (
<= max_size): Appendlinetocurrent_linesand add1 + len(line)tocurrent_length. - Does not fit (or no chunk is open yet): If
current_linesis non-empty, join and save it tochunks. Then start a freshcurrent_linescontaining all parent lines fromactive_headersfollowed byline, and compute its startingcurrent_length.
- Fits (
Trace Example 2 step by step
Let us trace
split_markdown("# Manual\n## Auth\n### OAuth\ntoken flow\n\n## Billing\ninvoices", max_size=37):Line Parents on stack Fit check Current chunk lines Len ------------ --------------------------------- -------------------- -------------------------------------------------- --- "# Manual" [] first line -> open ["# Manual"] 8 "## Auth" ["# Manual"] 8 + 1 + 7 = 16 <= 37 ["# Manual", "## Auth"] 16 "### OAuth" ["# Manual", "## Auth"] 16 + 1 + 9 = 26 <= 37 ["# Manual", "## Auth", "### OAuth"] 26 "token flow" ["# Manual", "## Auth", "### OAuth"] 26 + 1 + 10 = 37 <= 37 ["# Manual", "## Auth", "### OAuth", "token flow"] 37 "" (skipped blank line) - (unchanged) 37 "## Billing" pop OAuth, Auth -> ["# Manual"] 37 + 1 + 10 = 48 > 37 emit chunk 1; open ["# Manual", "## Billing"] 19 "invoices" ["# Manual", "## Billing"] 19 + 1 + 8 = 28 <= 37 ["# Manual", "## Billing", "invoices"] 28 (end) flush final chunk emit chunk 2Chunk 1 is
"# Manual\n## Auth\n### OAuth\ntoken flow"(37chars) and Chunk 2 is"# Manual\n## Billing\ninvoices"(28chars). Closed headings## Authand### OAuthwere popped cleanly before Chunk 2 opened.Complete solution
Putting the header helper and the four-phase loop together gives the complete solution:
from typing import Any, Dict, List, Optional, Set, Tuple # Whitespace and chunking assumptions: # 1. Input text is split on "\n". Blank or whitespace-only lines are ignored so no chunk # contains empty filler; non-blank lines keep their exact characters and indentation. # 2. Lines inside a chunk are joined with "\n", with no leading or trailing newline. # 3. Chunks are packed greedily: we only close the current chunk when appending the next # line would exceed max_size. # 4. If a single line (plus its parent headers) exceeds max_size, it is placed into its # own chunk intact rather than cut mid-line. def get_header_level(line: str) -> int: """Return 1..6 if `line` starts with 1..6 '#' characters followed by ' ', else 0.""" hash_count = 0 while hash_count < len(line) and line[hash_count] == "#": hash_count += 1 # A valid Markdown header needs 1 to 6 leading '#' characters AND a space right after. if 1 <= hash_count <= 6 and hash_count < len(line) and line[hash_count] == " ": return hash_count return 0 def split_markdown(markdown: str, max_size: int) -> list[str]: # active_headers: stack of (level, header_line) from outermost to innermost, # e.g. [(1, "# Title"), (2, "## Section")] active_headers: List[Tuple[int, str]] = [] # current_lines: lines accumulated in the chunk currently being built current_lines: List[str] = [] # current_length: exact character length of "\n".join(current_lines) current_length = 0 chunks: List[str] = [] for line in markdown.split("\n"): # Phase 1: skip empty or whitespace-only lines. if line.strip() == "": continue level = get_header_level(line) # Phase 2: if this line is a header, close any active headers at the same or deeper # level (>=) BEFORE choosing a chunk, so closed siblings are never repeated as context. if level > 0: while active_headers and active_headers[-1][0] >= level: active_headers.pop() # At this exact point, `active_headers` holds only the true parent headers of `line`. # Phase 3: try to append `line` to the current chunk (+1 accounts for the joining "\n"). # Use <= because a chunk of length equal to max_size is still valid. if current_lines and current_length + 1 + len(line) <= max_size: current_lines.append(line) current_length += 1 + len(line) else: # Close the finished chunk (if one is open) and start a fresh chunk with parent headers. if current_lines: chunks.append("\n".join(current_lines)) current_lines = [] for _, header_line in active_headers: current_lines.append(header_line) current_lines.append(line) current_length = len("\n".join(current_lines)) # Phase 4: push the new header AFTER placing it in `current_lines`, so a header line # starting a new chunk is not duplicated as its own parent context. if level > 0: active_headers.append((level, line)) # Flush the final chunk if the document had at least one non-blank line. if current_lines: chunks.append("\n".join(current_lines)) return chunks✅ Submit now — all tests should pass.
Intuition & how it works
Imagine printing a long reference manual where a single chapter spans several pages, and the printer stamps a running breadcrumb banner at the top of each new page — such as Chapter 1 > Section B — so a reader opening directly to page 5 immediately knows where they are. Splitting Markdown for search or language-model indexing has the exact same goal: each chunk is one "page" capped at max_size characters, and any chunk starting mid-section must repeat the chain of outer headers still active at that point.
A naive slicer that cuts the raw string every max_size characters breaks lines in half and loses all section titles. Even splitting line by line falls short if you only remember the single most recent header (which forgets outer parent titles like # Chapter 1 above ## Section B) or if you keep every header seen so far (which keeps finished sibling sections like ## Section A after ## Section B has already begun).
To keep the exact breadcrumb trail at every line, we use a monotonic stack — a list where items are kept in strictly increasing order from bottom to top by popping any entries that are greater than or equal to a newly arriving level. We also use greedy packing, meaning we keep appending lines to the current chunk until the next line no longer fits. Let us trace Example 1 (max_size = 30) on # Guide, ## Setup, Install SDK, Set API key:
1. # Guide (level 1) opens Chunk 1 ("# Guide", length 7), and the stack becomes [(1, "# Guide")].
2. ## Setup (level 2) fits (7 + 1 + 8 = 16 <= 30), so Chunk 1 becomes "# Guide\n## Setup", and the stack becomes [(1, "# Guide"), (2, "## Setup")].
3. Install SDK fits (16 + 1 + 11 = 28 <= 30), so Chunk 1 becomes "# Guide\n## Setup\nInstall SDK".
4. Set API key would push Chunk 1 to 28 + 1 + 11 = 40 > 30, so we close Chunk 1 and open Chunk 2 with the stack headings plus Set API key: "# Guide\n## Setup\nSet API key" (length 28).
Complexity
Let L be the number of characters in the input markdown string and S be the total number of characters across all returned chunks (S includes repeated parent headers).
- Time: O(L + S). Splitting on
"\n", checking for blank lines, and counting up to 6 leading#characters inspect each input character a constant number of times, costing O(L). Because valid header levels are strictly increasing from 1 to 6,active_headersholds at most 6 entries, so popping closed headers and copying active parents into a new chunk do O(1) stack operations per line, while building the output strings writesScharacters total. - Space: O(L + S). Storing the split input lines takes O(L) memory and storing the output chunks takes O(S) memory. The
active_headersstack holds at most 6 tuples at any moment, which is O(1) auxiliary space.
Edge cases
- Empty or whitespace-only document: Every line is skipped by
line.strip() == "", socurrent_linesstays empty and the function returns[]. - Plain text with no headers:
active_headersremains empty, so lines are simply grouped greedily up tomax_size. - Chunk boundary landing right on a header: Because we pop headers with level
>= levelbefore opening the new chunk and push the new header after, the new chunk includes only true outer parents and never repeats closed siblings or the new header twice. - Skipped header levels (e.g.,
# Afollowed directly by### C):### Chas level 3 > 1, so it sits cleanly on top of# A; a subsequent## B(level 2) pops### Cwhile keeping# A. - Exact size match (
current_length + 1 + len(line) == max_size): Allowed by<=, so we do not split a chunk one character early. - Header lookalikes:
#tag(no space),##(no space),####### seven(7 hashes), and# indented(leading space) all return level0and are treated as normal content lines. - Single line exceeding
max_size: Although normal inputs fit every line plus its ancestor headings insidemax_size, placingactive_headers + [line]into a freshcurrent_linesensures an oversized line is emitted intact in its own chunk rather than dropped or sliced mid-line.
Common mistakes
- Forgetting to count repeated headers or
"\n"separators towardmax_size: Every joined line after the first adds1 + len(line)characters because of the newline character between lines, and prepended parent headers also consume part of themax_sizebudget. - Popping with
ifinstead ofwhile: After# A,## B,### C, encountering## Dmust pop both### Cand## B, which requires awhileloop (while active_headers and active_headers[-1][0] >= level). - Updating the header stack at the wrong moment: Pushing a new header before building a fresh chunk duplicates that header at the top of the chunk; popping after building the fresh chunk leaks a closed sibling header into the new section.
- Re-joining
current_lineson every line to check its length: Callinglen("\n".join(current_lines + [line]))inside the loop copies the growing chunk repeatedly and degrades large-chunk performance from O(1) per line to O(chunk length) per line. - Emitting an empty first chunk
"": When the very first non-blank line arrives,current_linesis empty, so you must guardchunks.append(...)withif current_lines:.
Alternative approaches
- Preserve blank lines inside chunks: If downstream Markdown rendering needs empty lines to keep paragraphs separate, you can append blank lines when
current_linesis already open, while ignoring blank lines whenevercurrent_linesis empty (so no chunk ever begins with blank lines) and stripping trailing blank lines when closing a chunk. - Recursive section-first splitting: Parse the document into a tree of sections first, emit an entire section intact whenever it fits inside
max_size, and recursively split only sections that exceedmax_size. This avoids ending a chunk with a header whose body lands in the next chunk, though it produces more chunks that are less tightly packed.
Follow-up questions
- How can we avoid leaving a trailing heading at the bottom of a chunk when all of its body lines move into the next chunk? Hold newly seen heading lines in a temporary
pending_headersbuffer instead of appending them tocurrent_linesimmediately. When the next content line arrives, check whethercurrent_linescan fit allpending_headersplus that content line together; if not, closecurrent_linesfirst so the new chunk starts cleanly with the active heading hierarchy and the content line. Keep the current line-by-line behavior as a fallback in case a section has no body lines at all or a run of consecutive headings exceedsmax_size. - How would you support fenced code blocks so comment lines like
# initinside code are not treated as headings? Track anopen_fencestate whenever a line starts with at least three backticks (```) or three tildes (~~~). Whileopen_fenceis active, skipget_header_levelcompletely and treat every line — including# initand blank lines — as literal content until a closing line with at least as many matching fence characters appears. - What changes if an individual body line together with its ancestor headings exceeds
max_size? Measure the available body budgetmax_size - header_context_length, and split the oversized line into smaller sub-lines that each fit within that budget. Prefer breaking at the rightmost space before the budget so words stay whole, falling back to a hard character slice only when a single word is longer than the budget; every piece then gets the active ancestor headings prepended automatically. - How would you adapt the chunker if
max_sizewere measured in LLM tokens instead of character count? A token is a small word or sub-word piece produced by a model's tokenizer (for example,"chunking"might be two tokens"chunk"+"ing"). Replacelen(...)withlen(tokenize(...)), and remember that token counts are not strictly additive across"\n"because a tokenizer can merge characters across boundaries — so verifylen(tokenize("\n".join(candidate_lines))) <= max_sizewhen near the limit.
Follow-up questions
- How can we avoid leaving a trailing heading at the bottom of a chunk when all of its body lines move into the next chunk?
- How would you support fenced code blocks so comment lines like `# init` inside code are not treated as headings?
- What changes if an individual body line together with its ancestor headings exceeds `max_size`?
- How would you adapt the chunker if `max_size` were measured in LLM tokens instead of character count?
Similar questions
- Paginated Chat Transcript Loading and Token-Budget Eviction
- Design a Resilient AI Customer Support Chat Platform
- Paginated Record Collection and Token-Budget Compaction
- Paginated Conversation Loader with Suffix Token Trimming
- Drain Paginated Logs and Compact to a Byte Limit
- 2D Max Pooling with Source Coordinates
More Sierra interview questions
- Paginated Chat Transcript Loading and Token-Budget Eviction Medium
- Design a Resilient AI Customer Support Chat Platform Medium
- Paginated Record Collection and Token-Budget Compaction Medium Pro
- Paginated Conversation Loader with Suffix Token Trimming Medium Pro
- Drain Paginated Logs and Compact to a Byte Limit Medium Pro