Strip Line and Block Comments From Source Code Outside Strings

Last updated: November 29, 2026

Quick Overview

Given C-style source text, remove // line comments and /* block */ comments while leaving comment-like sequences inside string and character literals untouched, preserving newlines so line numbers stay stable.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


Given C-style source text, remove // line comments and /* block */ comments while leaving comment-like sequences inside string and character literals untouched, preserving newlines so line numbers stay stable.

Google's code tooling (formatters, code search indexing, linters) all need a comment-aware scanner, and this is a well-known onsite question in that style. The interviewer looks for an explicit state machine, correct handling of escapes inside strings, and thoughtful output choices such as keeping line numbers.

What the Interviewer Expects
  • Models the scanner with explicit states: code, line comment, block comment, string
  • Detects comment openers only in code state
  • Handles escaped quotes inside strings
  • Preserves newlines inside block comments and replaces each block with a space
  • Reports an unterminated block comment
Key Topics to Cover
State Machine
Lexing
String Literals
Escapes
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
  • Support Python, where # starts a comment and triple-quoted strings exist.
  • Preserve doc comments (/** ... */) but strip ordinary ones.
  • How does C++ raw string syntax R"(...)" change the state machine?
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
  • Input: a source string. Output: the same source without comments.
  • // runs to the end of the line; the newline itself is kept.
  • /* ... */ does not nest; newlines inside are kept, and the comme...
High-Level Design

Scan once with a four-state machine and one character of lookahead. In code state, // and /* switch states and are not copied; a quote switches to string state remembering which quote opened it. I...


Submit Your Answer
Markdown supported