Watch 10 video solutions for N-Repeated Element in Size 2N Array, a easy level problem involving Array, Hash Table. This walkthrough by codestorywithMIK has 4,425 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
You are given an integer array nums with the following properties:
nums.length == 2 * n.nums contains n + 1 unique elements.nums is repeated n times.Return the element that is repeated n times.
Example 1:
Input: nums = [1,2,3,3] Output: 3
Example 2:
Input: nums = [2,1,2,5,3,2] Output: 2
Example 3:
Input: nums = [5,1,5,2,5,3,5,4] Output: 5
Constraints:
2 <= n <= 5000nums.length == 2 * n0 <= nums[i] <= 104nums contains n + 1 unique elements and one of them is repeated exactly n times.Problem Overview: You are given an array of size 2N that contains N+1 unique values. Exactly one element appears N times while every other element appears once. The task is to identify the element that repeats N times.
Approach 1: HashMap / Hash Set (O(n) time, O(n) space)
The most direct solution uses a hash-based structure to track elements you've already seen. Iterate through the array once and insert each value into a HashSet (or store frequency in a HashMap). If an element already exists in the set, you've found the repeated element and can return it immediately. Hash lookups run in constant time on average, so the entire scan completes in O(n) time with O(n) auxiliary space. This approach works for any ordering of elements and is typically the expected interview solution when using a hash table.
Approach 2: Sorting (O(n log n) time, O(1) extra space)
Another option is to sort the array first. After sorting, identical elements become adjacent. Scan the sorted array and check neighboring values; the repeated element will appear multiple times consecutively. Sorting takes O(n log n) time, and the scan afterward is O(n). If the sorting algorithm is in-place, the extra memory cost is O(1) (or O(log n) depending on implementation). This method relies on the properties of a sorted array and avoids using additional hash storage, though it is slower than the optimal approach.
Recommended for interviews: The hash set approach is the cleanest and fastest solution with O(n) time complexity. It demonstrates familiarity with constant-time lookups using a hash table. Sorting works but is less optimal, so it is usually discussed as an alternative when minimizing extra memory or when sorting is already part of the workflow.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| HashMap / Hash Set | O(n) | O(n) | Best general solution with fast hash lookups |
| Sorting | O(n log n) | O(1) extra (depends on sort) | Useful when modifying the array is allowed and extra memory should be minimized |