Magicsheet logo

Remove Comments

Medium
60.9%
Updated 6/1/2025

Remove Comments

What is this problem about?

The Remove Comments interview question involves parsing source code represented as a list of strings and stripping out all comments. There are two types of comments: line comments (//), which ignore everything from the marker to the end of the line, and block comments (/* ... */), which can span multiple lines. The challenge is handling multi-line block comments correctly while preserving all non-comment characters in their proper positions.

Why is this asked in interviews?

This string parsing problem is a staple at companies like Uber, Goldman Sachs, Microsoft, and Google because it closely mirrors real-world tasks like writing a lexer or preprocessor. It requires careful state management — tracking whether you are currently inside a block comment — and handling edge cases like comments nested within string literals or block-comment markers spanning two lines. It evaluates attention to detail and systematic thinking.

Algorithmic pattern used

The pattern is line-by-line simulation with a state flag. Maintain a boolean in_block to track whether the current character is inside a /* */ block comment. Also maintain a buffer for the current line's non-comment characters. For each character, check if you're entering or exiting a block comment or encountering a line comment, and act accordingly. Append non-comment characters to the buffer; when a line ends (and you're not in a block), add the buffer to the result if it's non-empty.

Example explanation

Given source:

["int x = 1; /* start", "x = x + 1; /* end */", "return x;"]
  • Line 1: int x = 1; is kept, then /* starts a block comment.
  • Line 2: Still in block comment until */ is found. After that, nothing remains on the line.
  • Line 3: return x; is kept normally.

Result: ["int x = 1; ", "return x;"].

Common mistakes candidates make

  • Forgetting that a block comment can begin and end on the same line, leaving remaining characters on that line valid.
  • Not resetting the line buffer correctly when a block comment ends mid-line.
  • Treating // inside an active block comment as a line comment — it should be ignored.
  • Appending empty lines to the result when the entire line was a comment.

Interview preparation tip

For the Remove Comments coding problem, draw out a state diagram before coding: two states (normal mode, block-comment mode) with transitions on //, /*, and */. This makes the logic crystal clear. Interviewers at Hudson River Trading and Google often look for candidates who can enumerate edge cases explicitly — mention cases like /* comment */ all on one line and // inside a block comment to show thoroughness.

Similar Questions