algoadvance

Leetcode 722. Remove Comments

Problem Statement

Leetcode Problem 722 - Remove Comments

You are given a list of strings source where each string represents a single line of source code. This list of source code is to be viewed as an entire concatenated string, with each line being concatenated end-to-end with a newline delimiter.

You need to remove the comments from the source code. The comment types are:

  1. Line comments (//): These comments start with // and extend to the end of a line.
  2. Block comments (/* */): These comments start with /* and extend to the next occurrence of */. These can span multiple lines.

Return the source code after removing the comments. The result should be a list of strings, where each string represents a single line of the resulting code.

Clarifying Questions

  1. Input Constraints:
    • Is the input guaranteed to be valid C-style source code?
    • What is the maximum length for each line, and how many lines can there be?
  2. Output Format:
    • Should the output exactly mirror the input’s line breaks, just without comments?

Given that these are typical problems, let’s proceed with the structure assuming sane inputs.

Strategy

  1. Initialize a few variables to keep track of the state:
    • in_block_comment (boolean) to check if we are inside a block comment.
    • result to store the processed lines of code.
    • new_line to collect characters for the current line being processed.
  2. Iterate through each line:
    • If not in a block comment, check for line or block comment initiation.
    • If inside a block comment, search for its termination.
    • Collect characters not part of comments into the new_line list.
  3. Combine and return the result as a list of strings.

Code

Here is how you might implement this in Java:

import java.util.ArrayList;
import java.util.List;

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

        for (String line : source) {
            int i = 0;
            if (!inBlockComment) {
                newLine = new StringBuilder();
            }
            while (i < line.length()) {
                if (!inBlockComment && i + 1 < line.length() && line.charAt(i) == '/' && line.charAt(i + 1) == '/') {
                    break; // Line comment detected, ignore rest of the line
                } else if (!inBlockComment && i + 1 < line.length() && line.charAt(i) == '/' && line.charAt(i + 1) == '*') {
                    inBlockComment = true; // Block comment starts
                    i++;
                } else if (inBlockComment && i + 1 < line.length() && line.charAt(i) == '*' && line.charAt(i + 1) == '/') {
                    inBlockComment = false; // Block comment ends
                    i++;
                } else if (!inBlockComment) {
                    newLine.append(line.charAt(i)); // Add non-comment characters
                }
                i++;
            }
            if (!inBlockComment && newLine.length() > 0) {
                result.add(newLine.toString());
            }
        }
        return result;
    }

    public static void main(String[] args) {
        RemoveComments rc = new RemoveComments();
        String[] source = {
                "/*Test program */", 
                "int main()", 
                "{ ", 
                "  // variable declaration ",
                "int a, b, c;", 
                "/* This is a test",
                "   multiline  ",
                "   comment for ",
                "   testing */", 
                "a = b + c;", 
                "}"
        };
        List<String> output = rc.removeComments(source);
        for (String line : output) {
            System.out.println(line);
        }
    }
}

Time Complexity

This approach ensures that the entire source code is processed efficiently while properly handling nested and multiline comments.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI