Solution to Leetcode problem 961 N-Repeated Element in Size 2N Array
This is the first problem of Leetcode contest 116. This is easy enough and I left below my solution in Java.
Given an array A
of size 2N
, containing N+1
distinct elements with one element appearing N
times exactly. Return that element.
One could simply follow the question and count the number of times each element occurs in A
in a Map<Integer, Integer>
, but you could also notice that all the other N elements must appear only once. Therefore the question becomes which element appears at least twice in the array. To answer this question, you only need to iterate through A
remembering all previous elements encountered (in a Set
for instance). This is what I have done in the solution below.
class Solution {
public int repeatedNTimes(int[] A) {
Set<Integer> seenNumbers = new HashSet<>();
for (int num : A) {
if (seenNumbers.contains(num)) {
return num;
}
seenNumbers.add(num);
}
// Should not be reached
return 0;
}
}