Both approaches are almost identical in terms of algorithmic complexity.
The first difficulty of the approach is O(N * N) , where N is the length of the array. I donโt think itโs necessary to explain why, but just in case, these nested loops take N * N units of time, which gives complexity.
As for the second approach - the presence of a HashSet allows you to search with constant complexity ( O(1) ), since the search is based on a hashed String value. You might think that this approach is more efficient, but in reality it is not so much, because we need to meet the paste operation on a HashSet .
Adding to a HashSet has O(N) complexity (worst case scenario). For N String objects, you can have N insert operations, which again gives O(N * N) complexity.
So, to summarize, both approaches have similar costs. I would prefer the second option, although it would be more readable.
source share