#961

N-Repeated Element in Size 2N Array

Easy
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a HashMap allows us to count occurrences of each element in a single pass through the array, making it much more efficient.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a HashMap to keep track of the counts of each element.
  2. 2Step 2: Loop through the array and populate the HashMap with counts.
  3. 3Step 3: Check the HashMap for the element that has a count of n and return it.
solution.py8 lines
1# Full working Python code
2
3def repeatedNTimes(nums):
4    counts = {}
5    for num in nums:
6        counts[num] = counts.get(num, 0) + 1
7        if counts[num] == len(nums) // 2:
8            return num

Complexity note: This complexity is due to the single pass through the array to count occurrences, and the space is used to store counts in the HashMap.

  • 1The problem guarantees that there is exactly one element that is repeated n times, which simplifies our search.
  • 2Using a HashMap allows us to efficiently count occurrences without needing nested loops.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.