Remove Comments — LeetCode 722 Python Solution

MediumArrayString
Problem
#722
Pattern
Hash Map
Reading time
5 min

The problem

Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the ith line of the source code.

Example

Input
source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"]
Output
["int main()","{ "," ","int a, b, c;","a = b + c;","}"]
Explanation
The line by line code is visualized as below:

Python solution

Python
class Solution:
    def removeComments(self, source: List[str]) -> List[str]:
        ans = []
        t = []
        block_comment = False
        for s in source:
            i, m = 0, len(s)
            while i < m:
                if block_comment:
                    if i + 1 < m and s[i : i + 2] == "*/":
                        block_comment = False
                        i += 1
                else:
                    if i + 1 < m and s[i : i + 2] == "/*":
                        block_comment = True
                        i += 1
                    elif i + 1 < m and s[i : i + 2] == "//":
                        break
                    else:
                        t.append(s[i])
                i += 1
            if not block_comment and t:
                ans.append("".join(t))
                t.clear()
        return ans

Complexity

MeasureComplexity
TimeO(L)
SpaceO(L), where L is the total length of the source code auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 722. Remove Comments is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 722. Remove Comments?
LeetCode 722. Remove Comments is rated Medium on LeetCode.
What is the time complexity of LeetCode 722. Remove Comments?
The Python solution on this page runs in O(L).
What is the space complexity of LeetCode 722. Remove Comments?
The Python solution on this page uses O(L), where L is the total length of the source code auxiliary space.
What topics does LeetCode 722. Remove Comments cover?
LeetCode 722. Remove Comments is tagged Array and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview