// Time complexity is O(N * M), where N is the number of lines and M is the max length of a line.
// String builder append is an amortised O(1) operation as well as appending to the list.
// Space complexity is O(N * M), we need to store the entire input when there are no comments.
class Solution {
  public List<String> removeComments(String[] source) {
    ArrayList<String> lines = new ArrayList<String>();
    boolean multiline = false;
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < source.length; i++) {
      String line = source[i];
      int curr = 0, len = line.length();

      while (curr < len) {
        char t = line.charAt(curr);
        switch (t) {
          case '/':
            if (!multiline && curr + 1 < len && line.charAt(curr + 1) == '/') {
              if (sb.length() > 0) {
                lines.add(sb.toString());
                sb.setLength(0);
              }
              curr = len;
            } else if (!multiline && curr + 1 < len && line.charAt(curr + 1) == '*') {
              multiline = true;
              curr += 2; // skip '/*'
            } else if (multiline) {
              curr++;
            } else {
              sb.append(t);
              curr++;
            }
            break;
          case '*':
            if (multiline && curr + 1 < len && line.charAt(curr + 1) == '/') {
              curr += 2; // skip '*/'
              multiline = false;
            } else if (multiline) {
              curr++;
            } else {
              sb.append(t);
              curr++;
            }
            break;
          default:
            if (!multiline) {
              sb.append(t);
            }
            curr++;
            break;
        }
      }

      if (!multiline && sb.length() > 0) {
        lines.add(sb.toString());
        sb.setLength(0);
      }
    }

    return lines;
  }
}

@@ -276,16 +276,495 @@
 mments.%0A
+//%0A// Test cases:%0A//%0A// %5B%22int main() %7B // comment1%22, %22  int a = 1; /* line0%22, %22  line1%22, %22  line2%22, %22  */ if (true) %7B%22, %22    // line3%22, %22    return 0; // line4%22, %22  %7D else %7B%22, %22    /* line5 */ return 1;%22, %22  %7D%22, %22  // line6%22, %22%7D /* line7%22, %22*/%22%5D%0A// %5B%22// comment%22%5D%0A// %5B%22/* comment */%22%5D%0A// %5B%22/* comment%22, %22 comment */ %22%5D%0A// %5B%22struct Node%7B%22, %22    /*/ declare members;/**/%22, %22    int size;%22, %22    /**/int val;%22, %22%7D;%22%5D%0A// %5B%22/* 8 * 5 */%22%5D%0A// %5B%22/* 8 */ 5 */%22%5D%0A// %5B%22/*/ comment/**/%22%5D%0A//%0A
 class So

add test cases