2

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());
    }
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28
  • 2
    If the addresses are all IPv4, you get a space advantage by saving them as Integer values rather than Strings. – user15187356 Apr 16 '21 at 21:50
  • So should I take remove all the dots and take the IP as a number? because it had to read them with that format. – Razvan Nicolae Marghitas Apr 16 '21 at 22:01
  • 1
    @RazvanNicolaeMarghitas Check https://stackoverflow.com/questions/12057853/how-to-convert-string-ip-numbers-to-integer-in-java on how to convert an IPv4 address to an int/long. – Progman Apr 16 '21 at 22:03
  • 1
    Make sure it's a unsigned 8bit integer, if that's the route you go, for maximum memory savings. – Richard Barker Apr 16 '21 at 22:05
  • Just an aside, in the real world this doesn't quite work, because NAT and such will use the same IP address for different people. But also in the real world it's often close enough, so it's not that big of a deal. (But that's why the internet uses cookies instead of IP addresses, because if you want it to work 100% of the time then you can't use IP addresses.) – markspace Apr 16 '21 at 22:12
  • 2
    No - don't just remove the dots. You will fail to distinguish 1.23.4.5 from 1.2.34.5. Try `Inet4Address.getByName(str).getAddress()` to get 4 bytes. – user15187356 Apr 16 '21 at 22:48

0 Answers0