N-Repeated Element in Size 2N Array (LeetCode 961): Solution and Explanation
An array of length 2n holds n + 1 distinct values, and one of them fills n slots. Find that value.
Intuition
Every value except one appears exactly once. So the moment you find two equal values anywhere, you have found the answer.
A hash set finds the first repeat easily, but there is a neater observation. The repeated value takes up half the array, so its copies cannot all be spread far apart. If every two copies were at least 4 positions apart, n copies would need about 4n slots, and there are only 2n.
Working through the small cases shows that two copies are always within 3 positions of each other. So comparing each value with its neighbours at distance 1, 2 and 3 is guaranteed to find a matching pair, with no extra memory.
Approach: Check gaps 1, 2 and 3
- For gap = 1, compare nums[i] with nums[i + 1] for every i. Return nums[i] on a match.
- If nothing matched, repeat with gap = 2.
- If nothing matched, repeat with gap = 3. A valid input always matches by now.
- Return -1 only as a fallback for invalid input.
Step-by-step example
nums = [1,2,3,3]
- Gap 1, i = 0: nums[0] = 1 and nums[1] = 2 differ.
- Gap 1, i = 1: nums[1] = 2 and nums[2] = 3 differ.
- Gap 1, i = 2: nums[2] = 3 and nums[3] = 3 are equal.
- Only the repeated value can appear twice, so return 3.
Code: Python, Java, C++
1class Solution:
2 def repeatedNTimes(self, nums: List[int]) -> int:
3 for gap in range(1, 4):
4 for i in range(len(nums) - gap):
5 if nums[i] == nums[i + gap]:
6 return nums[i]
7 return -11class Solution {
2 public int repeatedNTimes(int[] nums) {
3 for (int gap = 1; gap <= 3; gap++) {
4 for (int i = 0; i + gap < nums.length; i++) {
5 if (nums[i] == nums[i + gap]) {
6 return nums[i];
7 }
8 }
9 }
10 return -1;
11 }
12}1class Solution {
2public:
3 int repeatedNTimes(vector<int>& nums) {
4 for (int gap = 1; gap <= 3; gap++) {
5 for (int i = 0; i + gap < (int)nums.size(); i++) {
6 if (nums[i] == nums[i + gap]) {
7 return nums[i];
8 }
9 }
10 }
11 return -1;
12 }
13};Time and space complexity
O(n)
Each gap pass makes fewer than 2n comparisons, and there are at most three passes.
O(1)
Only the loop indices are stored.
Other approaches
Hash set (time O(n), space O(n))
Walk the array and add each value to a set. The first value already in the set is the answer. It is the most direct approach and runs in one pass.
Sort and check the middle (time O(n log n), space O(1) to O(n))
After sorting, the repeated value covers half the array, so it must be at index n - 1 or n. Compare nums[n - 1] with its neighbours to decide which.
Random pairs (time O(1) expected, space O(1))
Pick two different random indices until their values match. Each try succeeds with probability about 1/4, so the expected number of tries is constant.
Common mistakes
- Only checking neighbours (gap 1). In [5,1,5,2,5,3,5,4] the copies of 5 are never adjacent.
- Stopping at gap 2. In [9,1,2,9] the only two copies are 3 apart.
- Counting with a full frequency map and then searching for count n. It works but does more work than needed, since any repeat is the answer.
Frequently asked questions
Why is a gap of 3 always enough?
If two copies of the repeated value were never within 3 positions of each other, consecutive copies would be at least 4 apart, so n copies would need more than 2n slots once n is at least 2. The only tight case is n = 2 with an array like [x,a,b,x], where the gap is exactly 3.
Why is any equal pair the answer?
All other values appear exactly once, so the only value that can occur at two different indices is the repeated one.
Is the hash set version acceptable in an interview?
Yes. It is O(n) time and simple. Mentioning the O(1) space gap trick as a follow-up shows you noticed the structure of the input.