-8

This program takes n integers in the list and then gives the count of the next t numbers entered by the user. If the numbers are in the list it prints the count and if it is not then it gives the "NOT PRESENT" message. I want to know if I can reduce its time and space complexity or do I have to take another approach for the program.

   import java.util.*;
    class Memorise_Me
    {
       public static void main(String args[])
       {
          Scanner sc=new Scanner(System.in);
          int n=sc.nextInt();
          List<Integer> list=new ArrayList<Integer>(n);
          while(n>0)
          {
            list.add(sc.nextInt());
            n--;
          }
        int t=sc.nextInt();
        int x,count=0;
        while(t>0)
        {
           x=sc.nextInt();
           count=Collections.frequency(list,x);
           if(count==0)
            System.out.println("NOT PRESENT");
           else
            System.out.println(count);
          t--;
        }
        sc.close();
    }
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Gaurav Bahadur
  • 189
  • 2
  • 14

1 Answers1

1

Almost all that this code do is organizing input and output except only this line: count=Collections.frequency(list,x); This is the only line where real computations happen. Actually, it's time and space complexity is determined by the standard java.util.Collections.frequency method which should have pretty good time and space characteristics for such a trivial case.

  • You could use a map instead of the list and store only counts (meaning that number is the key and number of its occurrences is the value). This way you don't need to traverse the list and count frequency of an item each time a user inputs value. On the other hand, you are going to search for an item on the map each time a user adds new value. – Vitaliy Ivanov Aug 20 '18 at 09:08