Split Markdown Into Header-Aware Chunks
SierraSoftware Engineer · Technical ScreenLast updated
This question evaluates string parsing, stateful text-processing, and algorithmic chunking skills, focusing on hierarchical header tracking and enforcing size constraints while preserving document order.
Implement a function that splits a Markdown document into ordered chunks, where each chunk must not exceed a given size limit.
A Markdown header is a line that starts with one to six # characters followed by a space, such as # Title or ## Section. Non-header lines belong to the current active header hierarchy.
When a new chunk starts in the middle of a section, the chunk must begin by repeating all active parent headers for the first content line in that chunk. For example, if a paragraph belongs under # Header 1 and ## Header 2, and a chunk boundary occurs immediately before that paragraph, the new chunk should start with:
# Header 1
## Header 2
followed by the paragraph.
Write a function such as:
def split_markdown(markdown: str, max_size: int) -> list[str]:
pass
Requirements:
- Preserve the original order of the document content.
- Each returned chunk must have length at most
max_size. - Header context added to a chunk counts toward the size limit.
- Header hierarchy should be updated correctly when encountering headers of different levels.
- You may assume that any single indivisible line plus its required header context can fit within
max_size. - Define and document any reasonable assumptions about whitespace and newline handling.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.