#722

Remove Comments

Medium
ArrayStringState ManagementString Parsing
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution processes the input in a single pass, maintaining a state to track whether we are inside a block comment. This avoids unnecessary string operations and improves efficiency.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize an empty result list and a boolean to track if we are in a block comment.
  2. 2Step 2: Loop through each line in the source code.
  3. 3Step 3: For each character in the line, check for the start or end of comments.
  4. 4Step 4: If we encounter '/*', set the block comment state to true; if we encounter '*/', set it to false.
  5. 5Step 5: If we are not in a block comment, add valid characters to a temporary line.
  6. 6Step 6: After processing the line, if it is not empty, add it to the result list.
solution.py25 lines
1# Full working Python code
2
3def removeComments(source):
4    result = []
5    in_block = False
6    for line in source:
7        temp_line = ''
8        i = 0
9        while i < len(line):
10            if not in_block:
11                if line[i:i+2] == '/*':
12                    in_block = True
13                    i += 2
14                elif line[i:i+2] == '//':
15                    break
16                else:
17                    temp_line += line[i]
18            else:
19                if line[i:i+2] == '*/':
20                    in_block = False
21                    i += 2
22            i += 1
23        if temp_line:
24            result.append(temp_line)
25    return result

Complexity note: The complexity is O(n) because we traverse each character in the input once, making it efficient for larger inputs.

  • 1Understanding the difference between line comments and block comments is crucial for parsing correctly.
  • 2Maintaining a state (in or out of a block comment) simplifies the logic for handling nested comments.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.