Python 0722.py
class Solution:
def removeComments(self, source: List[str]) -> List[str]:
inside = False # true if inside a C-style comment /* */
code = "" # code without comments, may span several input lines
for s in source:
skip = False # skip next character
for i in range(len(s)):
if skip:
skip = False
continue
one = s[i] # current character
two = s[i : i + 2] # current and the next character
if inside:
if two == "*/": # end of C-style comment
inside = False
skip = True
else:
if two == "//": # C++ comment: ignore rest of the line
break
if two == "/*": # start C-style comment
skip = True
inside = True
else: # no comment ...
code += one
if code and not inside: # skip empty lines
yield code
code = ""
Difficulty
and has an acceptance rate of about 40% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method removeComments that processes a list of source-code strings and returns the same code with all C-style (/* … */) and C++-style (// …) comments stripped out. The algorithm walks through each character of every line, tracks whether it is currently inside a block comment, and builds the resulting code line by line. When a line is completed and it contains non-empty code outside any block comment, the line is emitted via a generator.
Core Logic
The method begins by initializing two state variables: inside, a Boolean that indicates whether the parser is currently inside a block comment, and code, a string accumulator that holds the characters of the current output line.
inside = False # true if inside a C-style comment /* */
code = "" # code without comments, may span several input lines
The outer loop iterates over each input line s in source. For each line a local flag skip is set to False. This flag is used to skip the character that has already been examined as part of a two-character comment delimiter.
for s in source:
skip = False # skip next character
for i in range(len(s)):
if skip:
skip = False
continue
# processing of character at position i follows
Inside the inner loop the current character one and the two-character slice two are extracted.
one = s[i] # current character
two = s[i : i + 2] # current and the next character
Handling Block Comment Continuation
When inside is True, the parser is looking for the terminating sequence */. If two matches this sequence, the block comment ends, inside is cleared, and skip is set so that the second character of the delimiter (/) is not processed again.
if inside:
if two == "*/": # end of C-style comment
inside = False
skip = True
Handling Code Outside a Block Comment
When not inside a block comment, three distinct patterns are examined in order:
- The start of a line comment
//. Encountering this pattern causes an immediate break from the inner loop, discarding the remainder of the line.
if two == "//": # C++ comment: ignore rest of the line
break
- The start of a block comment
/*. The parser setsinsidetoTrueand marksskipso that the second character (*) is not added to the output.
if two == "/*": # start C-style comment
skip = True
inside = True
- Any other character that is not part of a comment delimiter is appended to
code.
else: # no comment ...
code += one
Emitting Completed Lines
After the inner loop finishes processing a line, the algorithm checks whether code holds any characters and whether the parser is not currently inside a block comment. If both conditions hold, the accumulated line is yielded and code is reset for the next line. This logic automatically discards empty lines that become blank after comment removal.
if code and not inside: # skip empty lines
yield code
code = ""
Edge Cases Addressed
The implementation correctly handles block comments that span multiple input lines. Because the inside flag persists across iterations of the outer loop, characters belonging to a block comment are ignored until the terminating */ is encountered, even if it appears on a later line.
It also deals with consecutive comment delimiters on the same line. The skip flag ensures that after recognizing a two-character delimiter, the parser does not mistakenly treat the second character as the start of another delimiter.
Lines that consist solely of a comment, or that become empty after comment removal, are not emitted because the final if code and not inside guard filters them out.
When a line comment // appears inside a block comment, the parser remains in the block comment state and does not prematurely terminate processing, because the inside branch takes precedence over the line-comment check.
Similarly, a block-comment start /* that appears inside an existing block comment is ignored, as the parser is already in the inside state and only looks for the closing */.
Performance Optimizations
The algorithm avoids constructing intermediate lists or substrings for each line. By using a single string accumulator code and appending characters directly, it minimizes memory allocations.
The skip flag eliminates the need to increment the loop index manually when a two-character delimiter is consumed; instead, the next iteration simply bypasses the already-processed character. This reduces the number of conditional checks per character.
Yielding lines as they become complete allows the method to operate as a generator, producing output lazily. Consumers can iterate over the result without requiring the entire output to be stored in memory at once.
The use of direct indexing (s[i] and s[i:i+2]) provides constant-time character access, and the inner loop runs exactly once per character of the input, ensuring linear traversal without redundant passes.
Overall, the design balances clarity with efficient in-place processing, handling all comment forms in a single pass while keeping auxiliary state to a minimum.
ELI5 - Simplified Explanation
Think of this code like a helpful robot reading a storybook that has some extra scribbles inside it. Sometimes people write notes for themselves in the margins, and the robot needs to clean the pages so only the real story remains.
The robot starts with a blank piece of paper and looks at every single letter on the page one by one. It keeps an eye out for a special secret code that marks the beginning of these scribbles. One kind of scribble starts with two little slashes, and the robot knows to just ignore everything else until it gets to the next line.
There is another kind of scribble that starts with a slash and a star. When the robot sees this, it stops reading the story and waits. Even if the scribble goes across many lines, the robot stays focused and ignores all the words until it sees a star and a slash, which is the magic signal that the scribble is finished.
Whenever the robot sees a normal word that is not part of a scribble, it writes that word down on a new clean page. Once it reaches the end of a line and knows there are no more whispers or notes hiding, it puts that clean line away and starts fresh with the next one. By the time the robot is finished, every bit of the story is neat and tidy with no messy notes left behind.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | |||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| JoshCrozier | JS | ||||||||
| Krazune | C++ | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| YuriSpiridonov | Python | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| JoshCrozier | JavaScript | ||||||||
| Krazune | C++ | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| YuriSpiridonov | Python | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 385: Mini Parser
Solved On The Same Day
- problem 1935: Maximum Number of Words You Can Type
- problem 907: Sum of Subarray Minimums
- problem 1798: Maximum Number of Consecutive Values You Can Make
- problem 871: Minimum Number of Refueling Stops
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality