简体   繁体   中英

Big O: what is the time complexity for this algorithm?

What is the best case and worst case time complexity for my method below?

I know ArrayList.add() is of O(1) time complexity but not sure about loaded.stream().distinct().collect(Collectors.toList());

  public static int countUnique(WordStream words) {

    ArrayList<String> loaded = new ArrayList<String>();
    ArrayList<String> empty = new ArrayList<String>();

    // Fill loaded with WordStream words
    for (String i : words) {
      loaded.add(i);
    }

    empty = (ArrayList<String>) loaded.stream().distinct().collect(Collectors.toList());

    return empty.size();
  }

Firstly, ArrayList() isn't O(1) for all operations, but it is for add() .

distinct() is O(n), because it must examine all elements. Each iteration is O(1) because it's backed by a HashSet, which is O(1).

You could replace your code with:

return (int)loaded.parallelStream().distinct().count();

which would be a lot faster, but still O(n)

You could implement this much more concisely by not using streams:

HashSet<String> loaded = new HashSet<>();
for (String i : words) {
  loaded.add(i);
}
return loaded.size();

You don't get much benefit from the parallel stream since you've got this loop being executed serially.

This approach would be O(n) also.


As noted by @Holger, if WordStream is a Collection (rather than a mere Iterable), it could be implemented even more concisely:

return new HashSet<>(words).size();

However, it is not specified in the question whether WordStream is actually a Collection .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM