I was working on this problem https://cses.fi/problemset/task/1660, and here's my code:
import java.util.*;
public class SubarraySumsI {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int N = in.nextInt();
int X = in.nextInt();
ArrayList <Long> prefix = new ArrayList <Long> ();
int count = 0;
prefix.add(0l);
long prefixsum = 0;
for (int a = 0; a < N; a++) {
prefixsum += in.nextInt();
prefix.add(prefixsum);
if (prefix.contains(prefixsum - X)) {
count++;
}
}
System.out.println(count);
in.close();
}
}
I noticed that on a lot of the test cases, it was really slow. However, if I just change prefix from an ArrayList to a HashSet, it suddenly becomes a lot faster.
I'm not that experienced with using Sets and HashSets yet, so can someone explain what the difference is between ArrayList and HashSet?