Comment Removal

Last Updated : 17 Aug, 2026

Given a string s representing a piece of code, remove all comments from the code and return the modified string. The code can contain two types of comments:

  • Single-line comments: Begin with // and continue until the end of the line (\n).
  • Multi-line comments: Begin with /* and end with */.

Note: Comments cannot be nested. The remaining code should preserve the original order of characters after removing all comments.

Examples:

Input: s = "#include int main(int *argc,char **argv){ // First line of code\\nprintf(\"Hello World!!! \"); return 0; }"
Output: "#include int main(int *argc,char **argv){ printf("Hello World!!! "); return 0; }"
Explanation: The comment starting with // and ending at the newline character is removed.

Input: s = "#include int main(int *argc,char **argv){ // First line of code\\nprintf(\"Hello World!!! \"); return 0; }"
Output: "#include int main(int *argc,char **argv){ printf("Hello World!!! "); return 0; }"
Explanation: The comment starting with // and ending at the newline character is removed.

[Naive Approach] Repeated Search and Erase - O(n^2) Time and O(1) Space

The idea is to repeatedly search for the next comment in the code and remove it immediately. If a single-line comment (//) is found, erase characters until the newline (\n). If a multi-line comment (/* ... */) is found, erase everything until the closing */. Continue this process until no comments remain.

  • Repeat until no comments are left in the string.
  • Search for the next occurrence of // and /*.
  • If neither is found, stop.
  • If // appears first, erase characters from // up to the next \n (inclusive if present).
  • Otherwise, erase characters from /* up to the matching */.
  • Return the modified string.
C++
#include <bits/stdc++.h>
using namespace std;

string removeComments(string &s)
{
    while (true)
    {
        // Find the next single-line and multi-line comments
        size_t singlePos = s.find("//");
        size_t multiPos = s.find("/*");

        // No comments left
        if (singlePos == string::npos && multiPos == string::npos)
            break;

        // Remove the earliest comment
        if (multiPos == string::npos || (singlePos != string::npos && singlePos < multiPos))
        {
            // Remove single-line comment
            size_t endPos = s.find("\\n", singlePos);

            if (endPos == string::npos)
                s.erase(singlePos);
            else
                s.erase(singlePos, endPos - singlePos + 2);
        }
        else
        {
            // Remove multi-line comment
            size_t endPos = s.find("*/", multiPos);

            if (endPos == string::npos)
                s.erase(multiPos);
            else
                s.erase(multiPos, endPos - multiPos + 2);
        }
    }

    return s;
}

int main()
{
    string s = "int a = 5; // comment\\nint b = 10; /* remove */ int c = 20;";
    cout << removeComments(s) << endl;

    return 0;
}
Java
import java.util.*;

class GFG {
    static String removeComments(String s)
    {
        while (true) {

            // Find the next single-line and multi-line
            // comments
            int singlePos = s.indexOf("//");
            int multiPos = s.indexOf("/*");

            // No comments left
            if (singlePos == -1 && multiPos == -1)
                break;

            // Remove the earliest comment
            if (multiPos == -1
                || (singlePos != -1
                    && singlePos < multiPos)) {

                // Remove single-line comment
                int endPos = s.indexOf("\\n", singlePos);

                if (endPos == -1)
                    s = s.substring(0, singlePos);
                else
                    s = s.substring(0, singlePos)
                        + s.substring(endPos + 2);
            }
            else {

                // Remove multi-line comment
                int endPos = s.indexOf("*/", multiPos);

                if (endPos == -1)
                    s = s.substring(0, multiPos);
                else
                    s = s.substring(0, multiPos)
                        + s.substring(endPos + 2);
            }
        }

        return s;
    }

    public static void main(String[] args)
    {
        String s = "int a = 5; // comment\\nint b = 10; /* remove */ int c = 20;";
        System.out.println(removeComments(s));
    }
}
Python
# Removes all comments from the given code string
def removeComments(s):
    while True:

        # Find the next single-line and multi-line comments
        single_pos = s.find("//")
        multi_pos = s.find("/*")

        # No comments left
        if single_pos == -1 and multi_pos == -1:
            break

        # Remove the earliest comment
        if multi_pos == -1 or (single_pos != -1 and single_pos < multi_pos):

            # Remove single-line comment
            end_pos = s.find("\\n", single_pos)

            if end_pos == -1:
                s = s[:single_pos]
            else:
                s = s[:single_pos] + s[end_pos + 2:]

        else:

            # Remove multi-line comment
            end_pos = s.find("*/", multi_pos)

            if end_pos == -1:
                s = s[:multi_pos]
            else:
                s = s[:multi_pos] + s[end_pos + 2:]

    return s


# Driver Code
if __name__ == "__main__":
    s = "int a = 5; // comment\\nint b = 10; /* remove */ int c = 20;"
    print(removeComments(s))
C#
using System;

class GFG {
    static string removeComments(string s)
    {
        while (true) {
            // Find the next single-line and multi-line
            // comments
            int singlePos = s.IndexOf("//");
            int multiPos = s.IndexOf("/*");

            // No comments left
            if (singlePos == -1 && multiPos == -1)
                break;

            // Remove the earliest comment
            if (multiPos == -1
                || (singlePos != -1
                    && singlePos < multiPos)) {
                // Remove single-line comment
                int endPos = s.IndexOf("\\n", singlePos);

                if (endPos == -1)
                    s = s.Substring(0, singlePos);
                else
                    s = s.Substring(0, singlePos)
                        + s.Substring(endPos + 2);
            }
            else {
                // Remove multi-line comment
                int endPos = s.IndexOf("*/", multiPos);

                if (endPos == -1)
                    s = s.Substring(0, multiPos);
                else
                    s = s.Substring(0, multiPos)
                        + s.Substring(endPos + 2);
            }
        }

        return s;
    }

    static void Main()
    {
        string s = "int a = 5; // comment\\nint b = 10; /* remove */ int c = 20;";
        Console.WriteLine(removeComments(s));
    }
}
JavaScript
// Removes all comments from the given code string
function removeComments(s)
{
    while (true) {

        // Find the next single-line and multi-line comments
        let singlePos = s.indexOf("//");
        let multiPos = s.indexOf("/*");

        // No comments left
        if (singlePos === -1 && multiPos === -1)
            break;

        // Remove the earliest comment
        if (multiPos === -1
            || (singlePos !== -1 && singlePos < multiPos)) {

            // Remove single-line comment
            let endPos = s.indexOf("\\n", singlePos);

            if (endPos === -1)
                s = s.substring(0, singlePos);
            else
                s = s.substring(0, singlePos)
                    + s.substring(endPos + 2);
        }
        else {

            // Remove multi-line comment
            let endPos = s.indexOf("*/", multiPos);

            if (endPos === -1)
                s = s.substring(0, multiPos);
            else
                s = s.substring(0, multiPos)
                    + s.substring(endPos + 2);
        }
    }

    return s;
}

// Driver Code
let s = "int a = 5; // comment\\nint b = 10; /* remove */ int c = 20;";
console.log(removeComments(s));

Output
int a = 5; int b = 10;  int c = 20;

[Expected Approach] Single Pass Traversal - O(n) Time and O(1) Space

The idea is to scan the code from left to right only once while keeping track of the current parsing state. Whenever the beginning of a comment is encountered, switch to the corresponding comment state and ignore all characters until the comment ends. Otherwise, copy the current character to the answer. Since each character is visited only once, this approach achieves O(n) time complexity.

  • Initialize an empty string ans and two boolean flags singleLine and multiLine as false.
  • Traverse the string character by character from left to right.
  • If inside a single-line comment, skip characters until the newline (\n) is reached.
  • If inside a multi-line comment, skip characters until the closing */ is found.
  • Otherwise, check for the start of // or /* comments and update the corresponding flag.
  • If the current character is not part of any comment, append it to ans. Finally, return ans.
C++
#include <bits/stdc++.h>
using namespace std;

string removeComments(string &s)
{
    string ans;
    bool singleLine = false;
    bool multiLine = false;

    for (int i = 0; i < s.size(); i++)
    {
        // Skip characters inside a single-line comment
        if (singleLine)
        {
            if (i + 1 < s.size() && s[i] == '\\' && s[i + 1] == 'n')
            {
                singleLine = false;
                i++;
            }
        }

        // Skip characters inside a multi-line comment
        else if (multiLine)
        {
            if (i + 1 < s.size() && s[i] == '*' && s[i + 1] == '/')
            {
                multiLine = false;
                i++;
            }
        }

        else
        {
            // Beginning of a single-line comment
            if (i + 1 < s.size() && s[i] == '/' && s[i + 1] == '/')
            {
                singleLine = true;
                i++;
            }

            // Beginning of a multi-line comment
            else if (i + 1 < s.size() && s[i] == '/' && s[i + 1] == '*')
            {
                multiLine = true;
                i++;
            }

            // Normal character
            else
            {
                ans += s[i];
            }
        }
    }

    return ans;
}

int main()
{
    string s = "int a = 5; // comment\\nint b = 10; /* remove */ int c = 20;";
    cout << removeComments(s) << endl;

    return 0;
}
Java
import java.util.*;

class GFG {
    static String removeComments(String s)
    {
        StringBuilder ans = new StringBuilder();

        boolean singleLine = false;
        boolean multiLine = false;

        for (int i = 0; i < s.length(); i++) {

            // Skip characters inside a single-line comment
            if (singleLine) {

                if (i + 1 < s.length()
                    && s.charAt(i) == '\\'
                    && s.charAt(i + 1) == 'n') {

                    singleLine = false;
                    i++;
                }
            }

            // Skip characters inside a multi-line comment
            else if (multiLine) {

                if (i + 1 < s.length() && s.charAt(i) == '*'
                    && s.charAt(i + 1) == '/') {

                    multiLine = false;
                    i++;
                }
            }

            else {
                
                // Beginning of a single-line comment
                if (i + 1 < s.length() && s.charAt(i) == '/'
                    && s.charAt(i + 1) == '/') {

                    singleLine = true;
                    i++;
                }

                // Beginning of a multi-line comment
                else if (i + 1 < s.length()
                         && s.charAt(i) == '/'
                         && s.charAt(i + 1) == '*') {

                    multiLine = true;
                    i++;
                }

                // Normal character
                else {
                    ans.append(s.charAt(i));
                }
            }
        }

        return ans.toString();
    }

    public static void main(String[] args)
    {
        String s = "int a = 5; // comment\\nint b = 10; /* remove */ int c = 20;";
        System.out.println(removeComments(s));
    }
}
Python
def removeComments(s):

    ans = []

    single_line = False
    multi_line = False

    i = 0

    while i < len(s):

        # Skip characters inside a single-line comment
        if single_line:

            if i + 1 < len(s) and s[i] == '\\' and s[i + 1] == 'n':
                single_line = False
                i += 1

        # Skip characters inside a multi-line comment
        elif multi_line:

            if i + 1 < len(s) and s[i] == '*' and s[i + 1] == '/':
                multi_line = False
                i += 1

        else:

            # Beginning of a single-line comment
            if i + 1 < len(s) and s[i] == '/' and s[i + 1] == '/':
                single_line = True
                i += 1

            # Beginning of a multi-line comment
            elif i + 1 < len(s) and s[i] == '/' and s[i + 1] == '*':
                multi_line = True
                i += 1

            # Normal character
            else:
                ans.append(s[i])

        i += 1

    return "".join(ans)


# Driver Code
if __name__ == "__main__":
    s = "int a = 5; // comment\\nint b = 10; /* remove */ int c = 20;"

    print(removeComments(s))
C#
using System;
using System.Text;

class GFG {
    static string removeComments(string s)
    {
        StringBuilder ans = new StringBuilder();

        bool singleLine = false;
        bool multiLine = false;

        for (int i = 0; i < s.Length; i++) {
            
            // Skip characters inside a single-line comment
            if (singleLine) {
                if (i + 1 < s.Length && s[i] == '\\'
                    && s[i + 1] == 'n') {
                    singleLine = false;
                    i++;
                }
            }

            // Skip characters inside a multi-line comment
            else if (multiLine) {
                if (i + 1 < s.Length && s[i] == '*'
                    && s[i + 1] == '/') {
                    multiLine = false;
                    i++;
                }
            }

            else {
                // Beginning of a single-line comment
                if (i + 1 < s.Length && s[i] == '/'
                    && s[i + 1] == '/') {
                    singleLine = true;
                    i++;
                }

                // Beginning of a multi-line comment
                else if (i + 1 < s.Length && s[i] == '/'
                         && s[i + 1] == '*') {
                    multiLine = true;
                    i++;
                }

                // Normal character
                else {
                    ans.Append(s[i]);
                }
            }
        }

        return ans.ToString();
    }

    static void Main()
    {
        string s = "int a = 5; // comment\\nint b = 10; /* remove */ int c = 20;";
        Console.WriteLine(removeComments(s));
    }
}
JavaScript
function removeComments(s)
{
    let ans = "";

    let singleLine = false;
    let multiLine = false;

    for (let i = 0; i < s.length; i++) {

        // Skip characters inside a single-line comment
        if (singleLine) {
            if (i + 1 < s.length && s[i] === "\\"
                && s[i + 1] === "n") {

                singleLine = false;
                i++;
            }
        }

        // Skip characters inside a multi-line comment
        else if (multiLine) {
            if (i + 1 < s.length && s[i] === "*"
                && s[i + 1] === "/") {

                multiLine = false;
                i++;
            }
        }

        else {

            // Beginning of a single-line comment
            if (i + 1 < s.length && s[i] === "/"
                && s[i + 1] === "/") {

                singleLine = true;
                i++;
            }

            // Beginning of a multi-line comment
            else if (i + 1 < s.length && s[i] === "/"
                     && s[i + 1] === "*") {

                multiLine = true;
                i++;
            }

            // Normal character
            else {
                ans += s[i];
            }
        }
    }
    return ans;
}

// Driver Code
let s = "int a = 5; // comment\\nint b = 10; /* remove */ int c = 20;";
console.log(removeComments(s));
Try It Yourself
redirect icon

Output
int a = 5; int b = 10;  int c = 20;
Comment