Ctrl K

Strip C-Style Comments

Medium
A program in a C-like language is given as a list of lines lines. Remove two kinds of comments from it: - // starts a **line** comment: it and everything to its right up to the end of the line are removed. - /* starts a **block** comment: everything up to the next */ is removed, even across several lines. The closing pair cannot overlap the opening one, so /*/ does not close the comment yet. Line breaks inside a block are removed too, so the parts of lines before and after the block are glued together. Whichever comment starts first wins: // inside a block means nothing, and neither does /* inside any comment. Quotes do not form string literals here; they do not protect text from removal. Return the code without comments in the same form, as a list of lines. Lines that end up empty are left out.
Example 1
lines=["x = 1; // init", "/* tmp", "y = 2; */ z = 3;", "// done"] → ['x = 1; ', ' z = 3;']

The first line keeps x = 1; (the space before the comment stays). The block comment swallows the second line and the start of the third, leaving z = 3;. The last line is all comment and disappears.

Example 2
lines=["go(/*a", "b*/1);"] → ['go(1);']

The block comment swallows the line break too, so the two lines merge into one: go(1);.

Example 3
lines=["a/*/b*/c", "d // e /* f"] → ['ac', 'd ']

/*/ does not close the comment yet; it ends at the */ after b. On the second line /* sits inside a line comment and opens nothing.

Constraints
  • 1 ≤ len(lines) ≤ 100
  • 0 ≤ len(lines[i]) ≤ 80
  • Lines consist of printable ASCII characters
  • Every block comment that opens is eventually closed
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsAnagram Buckets MediumWord Traced on a Letter Grid MediumSplit Into Dictionary Words MediumBiggest Number From Pieces MediumClosest Events in a Log Medium
loading Python…
Input
lines=["x = 1; // init", "/* tmp", "y = 2; */ z = 3;", "// done"]
Expected
['x = 1; ', ' z = 3;']

Run checks the first 3 tests in your browser. Submit checks all 85 tests on the server, hidden ones included.