Code360 powered by Coding Ninjas X Code360 powered by Coding Ninjas X

Remove Comments

Average time to solve is 15m
Contributed by
Asked in company
Goldman Sachs

Problem statement

You are given a text in the form of an array of strings. A string present at the (i+1)th index, can be assumed to be separated from the string at the ith index, by a newline character (i.e. ‘\n’).

In the given text, we have two types of comments: line comments and block comments.

The string “//” denotes the starting of a line comment, which represents that the rest of the characters to the right of this string and present in the same line, should be ignored.

And the strings “/” and “/” denote the starting and ending points of a block comment, which represents that all the characters between these two strings must be ignored. Note that block comments can span across multiple lines whereas line comments end at the same line.

Your task is to remove the comments from the given text and print the text in the same format.

The first comment is given precedence over the other i.e. if the string “//” occurs in a block comment, then it is ignored and/or if the string “/*” occurs in a line or a block comment, it is also ignored.

The starting and ending point of the block comment must be non-overlapping i.e. a string like “/*/” does not end the block comment, as the ending would be overlapping the beginning.

Every starting point of a block comment will have an ending point as well.

The (implicit) newline characters which may occur when a block comment spans multiple lines, must be deleted/removed.

The text doesn’t contain any single or double quotes characters.
Detailed explanation ( Input/output format, Notes, Images )
1 <= N <= 100
0 <= Length of ith String <= 5 * 10^3

Where  ‘N’ represents the number of lines in the given text.

Time Limit: 1 sec
Sample Input 1:
test case */
main() {
// Declare variables here.
int a = 2, b = 3, sum;
sum = a + b; // Find sum
Sample Output 1:
main() {
int a = 2, b = 3, sum;
sum = a + b;
Explanation 1:
Remove the line and block comments and print the resulting text. On removing comments, lines 1, 2 and 4 of the text becomes empty, so we do not output those lines.
Sample Input 2:
Coding/* Block comment
Spanning multiple lines */ Ninjas
Sample Output 2:
Coding Ninjas
Explanation 2:
Remove the block comments and print the resulting text. On removing the block comment, the implicit newline character also gets removed.
Full screen