I recently had an interview test with the following quite simple problem:
"You just launched a new website and you would want to see how many people access it. You don't have access to statistics, but you have a list with all the IPs that accessed your website. An IP shows up every time someone access your page. To find out how many people accessed your website you would want to count all the distinct IPs from the list.
Input Data: from console - first line N - natural number;after that N lines with 1 IP/line. Output Data: in console - a natural number with the number of distinct IPs. Restrictions: N<=100.000 IP format: [0-255].[0-255].[0-255].[0-255]
Example input:
5
0.0.0.1
0.0.0.2
0.0.0.1
125.23.34.125
0.0.0.1
Output:
3
Time limit: 1000ms Memory limit: 128MB
And they ran some tests on their platform and somehow my code didn't pass the last test due to memory because it used around 131k kB. Do you have any idea of improvement so I know in the future?
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int noOfIps = reader.nextInt();
reader.nextLine();
Set<String> uniqueIPs = new HashSet<String>();
for(int i=0;i<noOfIps;i++){
uniqueIPs.add(reader.nextLine());
}
System.out.print(uniqueIPs.size());
}
}