We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

N-Repeated Element in Size 2N Array

Number: 1001

Difficulty: Easy

Paid? No

Companies: Akamai


Problem Description

Given an array nums of length 2*n containing n+1 unique elements, where one single element is repeated exactly n times, return the element that is repeated n times.


Key Insights

  • The array has exactly 2*n elements.
  • There are n+1 unique elements, meaning one element repeats n times.
  • Tracking elements using a hash set allows quick identification of the repeated element.
  • The problem can be solved using a single pass (O(n) time complexity).

Space and Time Complexity

Time Complexity: O(n) - We iterate through the array once. Space Complexity: O(n) - We use extra space for a hash set to track seen elements.


Solution

We can solve the problem by using a hash set to maintain a record of elements we have already seen. As we iterate through the array, we check if the current element is in the hash set. If it is, that means it must be the element repeated n times, and we immediately return it. This approach leverages the O(1) average time complexity of hash set membership checks. An important gotcha is ensuring that we exit as soon as the repeated element is found, avoiding unnecessary further iterations.


Code Solutions

# Define the function to find the repeated element
def repeatedNTimes(nums):
    # Create a set to store seen numbers
    seen = set()
    # Loop through every number in the array
    for num in nums:
        # Check if the number is already in the set
        if num in seen:
            return num
        # Add the number to the set
        seen.add(num)

# Example usage:
# print(repeatedNTimes([1, 2, 3, 3]))
← Back to All Questions