Auto-Number Markdown Headings Into Hierarchical Section Labels

Last updated: November 29, 2026

Quick Overview

Given a Markdown document, prefix every ATX heading (# to ######) with a hierarchical section number such as 1, 1.2, or 1.2.1, resetting deeper counters when a shallower heading appears and ignoring hash lines inside fenced code blocks.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Given a Markdown document, prefix every ATX heading (# to ######) with a hierarchical section number such as 1, 1.2, or 1.2.1, resetting deeper counters when a shallower heading appears and ignoring hash lines inside fenced code blocks.

A Google Docs or internal documentation tooling question: generate the outline numbering a design doc template expects. The interviewer checks that you parse headings precisely, keep a counter stack with correct resets, and avoid false positives in code blocks and hashtags.

What the Interviewer Expects
  • Recognizes headings only with one to six hashes followed by a space
  • Maintains a list of counters indexed by level
  • Truncates deeper counters when a shallower heading appears
  • Ignores lines inside fenced code blocks
  • Defines behavior when a level is skipped
Key Topics to Cover
String Parsing
Counters and Stacks
Markdown
Hierarchical Numbering
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Generate a table of contents with anchor links next to the numbering.
  • Make the operation idempotent so running it twice does not double the numbers.
  • Support Setext headings (underlined with === or ---).
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • A heading line starts with 1 to 6 # and then a space; #hashtag is not a heading.
  • Lines between triple-backtick fences are code and never numbered.
  • A heading at level L increments counter `...
High-Level Design

Walk lines once, toggling an in_fence flag on fence lines. For a heading at level L, extend the counter list with zeros up to length L, truncate it to length L, and increment the last entry. T...


Submit Your Answer
Markdown supported