This is what I encountered solving leetcode problem 954. Array of Doubled Pairs.
Here's a global map which stores the count on each value. I use this function below to check if the values in the list (which is also in the map) are all paired (if the map has value
and value * 2
).
Map<Integer, Integer> map;
private boolean isPaired( List<Integer> list) {
for(int key : list) {
if (map.containsKey(key)) {
if (map.containsKey(key * 2)) {
updateMap(key);
updateMap(key * 2);
} else {
return false;
}
}
}
return true;
}
private void updateMap(int key) {
int value = map.get(key);
if (value - 1 == 0) {
map.remove(key);
} else {
map.put(key , value - 1);
}
}
with the case (9945 0s, 10052 1s and 10003 2s), it throws NullPointerException. Here's the exception message:
java.lang.NullPointerException
at line 54, Solution.updateMap
at line 44, Solution.isPaired
at line 26, Solution.canReorderDoubled
at line 54, __DriverSolution__.__helper__
at line 84, __Driver__.main
And as I changed the function isPaired
into the code below:
private boolean isPaired(List<Integer> list) {
for(int key : list) {
if (map.containsKey(key)) {
updateMap(key);
if (map.containsKey(key * 2)) {
updateMap(key * 2);
} else {
return false;
}
}
}
return true;
}
NullPointerException doesn't occur anymore. Why do these happen?
The NullPointerException (NPE) occurs in the first case because key
and key*2
are the same value when key=0
. The second version of the code tests for the presence of key*2
after the first mapping has already been removed so it doesn't encounter the NPE.