KatInterview

722. Remove Comments

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to remove C++ style comments from a given source code represented as an array of strings. There are two types of comments: line comments (//) and block comments (/* ... */). The main complexity lies in correctly handling the state of being inside or outside a block comment, especially since block comments can span multiple lines and effectively merge code from different lines.

Solution

Remove Comments in Python

class Solution:
    def removeComments(self, source: List[str]) -> List[str]:
        result = []
        in_block_comment = False
        current_line = ""

        for line in source:
            i = 0
            n = len(line)
            while i < n:
                if in_block_comment:
                    # If we are in a block comment, look for '*/'
                    if i + 1 < n and line[i:i+2] == '*/':
                        in_block_comment = False
                        i += 2
                    else:
                        i += 1
                else:
                    # If not in a block comment, look for '//' or '/*'
                    if i + 1 < n and line[i:i+2] == '//':
                        # Line comment, ignore the rest of the line
                        break
                    elif i + 1 < n and line[i:i+2] == '/*':
                        # Start of a block comment
                        in_block_comment = True
                        i += 2
                    else:
                        # Regular character, append to current line
                        current_line += line[i]
                        i += 1
            
            # At the end of a line, if not in a block comment, process the built line
            if not in_block_comment:
                if current_line:
                    result.append(current_line)
                # Reset for the next line of source code
                current_line = ""
        
        return result

Remove Comments in Java

class Solution {
    public List<String> removeComments(String[] source) {
        List<String> result = new ArrayList<>();
        boolean inBlockComment = false;
        StringBuilder currentLine = new StringBuilder();

        for (String line : source) {
            for (int i = 0; i < line.length(); ) {
                if (inBlockComment) {
                    // If we are in a block comment, look for '*/'
                    if (i + 1 < line.length() && line.charAt(i) == '*' && line.charAt(i + 1) == '/') {
                        inBlockComment = false;
                        i += 2;
                    } else {
                        i++;
                    }
                } else {
                    // If not in a block comment, look for '//' or '/*'
                    if (i + 1 < line.length() && line.charAt(i) == '/' && line.charAt(i + 1) == '/') {
                        // Line comment, ignore the rest of the line
                        break;
                    } else if (i + 1 < line.length() && line.charAt(i) == '/' && line.charAt(i + 1) == '*') {
                        // Start of a block comment
                        inBlockComment = true;
                        i += 2;
                    } else {
                        // Regular character, append to current line
                        currentLine.append(line.charAt(i));
                        i++;
                    }
                }
            }

            // At the end of a line, if not in a block comment, process the built line
            if (!inBlockComment) {
                if (currentLine.length() > 0) {
                    result.add(currentLine.toString());
                }
                // Reset for the next line of source code
                currentLine = new StringBuilder();
            }
        }
        return result;
    }
}

Remove Comments in C++

class Solution {
public:
    vector<string> removeComments(vector<string>& source) {
        vector<string> result;
        bool in_block_comment = false;
        string current_line = "";

        for (const string& line : source) {
            for (int i = 0; i < line.length(); ) {
                if (in_block_comment) {
                    // If we are in a block comment, look for '*/'
                    if (i + 1 < line.length() && line[i] == '*' && line[i+1] == '/') {
                        in_block_comment = false;
                        i += 2;
                    } else {
                        i++;
                    }
                } else {
                    // If not in a block comment, look for '//' or '/*'
                    if (i + 1 < line.length() && line[i] == '/' && line[i+1] == '/') {
                        // Line comment, ignore the rest of the line
                        break; 
                    } else if (i + 1 < line.length() && line[i] == '/' && line[i+1] == '*') {
                        // Start of a block comment
                        in_block_comment = true;
                        i += 2;
                    } else {
                        // Regular character, append to current line
                        current_line += line[i];
                        i++;
                    }
                }
            }

            // At the end of a line, if not in a block comment, process the built line
            if (!in_block_comment) {
                if (!current_line.empty()) {
                    result.push_back(current_line);
                }
                // Reset for the next line of source code
                current_line = "";
            }
        }
        return result;
    }
};

Remove Comments in TypeScript

function removeComments(source: string[]): string[] {
    const result: string[] = [];
    let inBlockComment = false;
    let currentLine = "";

    for (const line of source) {
        let i = 0;
        const n = line.length;
        while (i < n) {
            if (inBlockComment) {
                // If we are in a block comment, look for '*/'
                if (i + 1 < n && line.substring(i, i + 2) === '*/') {
                    inBlockComment = false;
                    i += 2;
                } else {
                    i++;
                }
            } else {
                // If not in a block comment, look for '//' or '/*'
                if (i + 1 < n && line.substring(i, i + 2) === '//') {
                    // Line comment, ignore the rest of the line
                    break;
                } else if (i + 1 < n && line.substring(i, i + 2) === '/*') {
                    // Start of a block comment
                    inBlockComment = true;
                    i += 2;
                } else {
                    // Regular character, append to current line
                    currentLine += line[i];
                    i++;
                }
            }
        }

        // At the end of a line, if not in a block comment, process the built line
        if (!inBlockComment) {
            if (currentLine.length > 0) {
                result.push(currentLine);
            }
            // Reset for the next line of source code
            currentLine = "";
        }
    }
    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.