Wednesday, April 4, 2018

Building a Smart IDE: Identifying comments - HackerRank Problem

Difficulty: $\mathtt{Very\ Very\ Easy}$

Find the problem definition @ HackerRank

Solution

Simply travers thorugh each line and display the line when you know the line or part of it is comment

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        boolean comment = false;
        while(sc.hasNext()) {
            String line = sc.nextLine();
            
            if (line.trim().startsWith("/*")) comment = true;
            
            if (comment || line.trim().startsWith("//")) {
                System.out.println(line.trim());
            } else if (line.contains("//")) {
                int index = line.indexOf("//");
                System.out.println(line.substring(index));
            }
            
            if (line.endsWith("*/")) {
                comment = false;
            }
        }
    }
}

    

Time Complexity

The while loop in the code runs for $n$ number of times $n$ being the number of lines in the input. Time complexity of each loop depends upon the time taken by the methods like startsWith(), trim(), contains(), indexOf(), endsWith() and substring() of the String class.

Assuming all these methods are optimised to have the complexity ${\cal O})(n)$, $n$ being lenght of each line, overall complexity of the above solution is ${\cal O})(N)$, $N$ being total length of all lines.

Notes

Above solution doesn't considers special cases as:
  • Comments like /* Comment */ is nested inside a code.
  • String like // is a part of String constant in a code
  • String like /* */ is a part of String constant in a code







2 comments:

  1. It was really nice article and provide valuable information on smart buildings IoT. I appreciate your knowledge. Thanks for sharing

    ReplyDelete
  2. Very significant Information for us, I have think the representation of this Information is actually superb one. This is my first visit to your site.
    best electronics shops in dubai

    ReplyDelete