961. N-Repeated Element in Size 2N Array
UnknownView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
N-Repeated Element in Size 2N Array (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Hash Table pattern in coding interviews. Use a HashSet; the first element that fails insertion is the repeated element.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Use a HashSet; the first element that fails insertion is the repeated element.
Related patterns: Array, Hash Table, Math
961.cs
C#
// Approach: Use a HashSet; the first element that fails insertion is the repeated element.
// Time: O(n) Space: O(n)
public class Solution
{
public int RepeatedNTimes(int[] nums)
{
// Create a HashSet to store unique elements
// Initial capacity is set to n/2 + 1 for optimization
HashSet<int> seenNumbers = new HashSet<int>(nums.Length / 2 + 1);
// Iterate through the array
for (int i = 0; ; ++i)
{
// Try to add current element to the set
// Add() returns false if element already exists
if (!seenNumbers.Add(nums[i]))
// Found the duplicate element that appears n times
return nums[i];
}
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)