Here you have a Java 8, please specify if you need a Java 7 solution.
Assumption 1: The ArrayList
s are not nulls.
Its time complexity is O(N), where N
is the size of any of the inputs.
Its memory complexity in addition to the input is 0(N)
In other words, its time and memory complexity are linear.
Theoretically you could have a constant O(1)
memory complexity, but it would involve removing elements from the a1
while adding them to the setA1
. In my opinion, this relies too much on garbage collector so hopefully this solution will be enough for you.
import java.util.*;
public class ArraySameValuesSolver {
public boolean of(List<String> list1, List<String> list2) {
if (list1.size() != list2.size())
return false;
Map<String, Integer> occ = new HashMap<>();
list1.stream().forEach(s -> incrementOccurences(occ, s));
for (String s: list2) {
decrementOccurrences(occ, s);
if (occ.get(s) < 0)
return false;
}
return true;
}
private void incrementOccurences(Map<String, Integer> occ, String s) {
if (!occ.containsKey(s))
occ.put(s, 1);
else
occ.put(s, occ.get(s) + 1);
}
private void decrementOccurrences(Map<String, Integer> occ, String s) {
if (!occ.containsKey(s))
occ.put(s, -1);
else
occ.put(s, occ.get(s) - 1);
}
}
arraylists
have same elements without comparing each one of them. Hence, best you can do isO(N)
– Caterwaulif (a, b) == (b, a, b)
, as thesize()
comparison becomes meaningless, and you must then check for elements that exist in the hash table, but not in the second sequence. – Desiderative