Senior
//Given an array of numbers where all numbers except one have a pair, //find the number that appears only once // <= [1, 0, 3, -2, 9, 9, 1, -2, 0] // => 3 int find(int[] arr){ Map<Integer, Integer> freq = new HashMap<>(); for (int i : arr){ freq.merge(i, 1, Integer::sum); } return freq.entrySet().stream() .filter(e -> e.getValue() == 1) .findFirst().get().getKey() .orElseThrow( () -> new NoSuchElementException("no unique elements") ); }
sobes.tech AI
Answer from AI
The provided code implements a search for a unique number in an array where all numbers except one appear in pairs.
Solution idea:
- Use a
Map<Integer, Integer>to count the occurrences of each number. - Then find the element with a frequency of 1.
However, there is an error in the code: the method findFirst().get() returns an Optional object, and calling orElseThrow after get() is incorrect. You should first call orElseThrow on the Optional, then get the key.
Corrected version:
int find(int[] arr) {
Map<Integer, Integer> freq = new HashMap<>();
for (int i : arr) {
freq.merge(i, 1, Integer::sum);
}
return freq.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst()
.orElseThrow(() -> new NoSuchElementException("no unique elements"));
}
This method efficiently finds the number that occurs once in O(n) time.