↓Skip to main content
  1. LeetCode/

LeetCode 961: N-Repeated Element in Size 2N Array

·1 min· ·
LeetCode Easy Array Hash-Table Pigeonhole-Principle
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-26

  • Submissions: Accepted ×3

Approach
#

An array of length 2n holds n + 1 distinct values, one repeated n times and the rest once. So add values to a set while scanning; the first repeat is the answer (Hash Table). For O(1) space, the repeated value must meet itself within distance 3 somewhere.

My Solution
#

class Solution:
    def repeatedNTimes(self, nums: List[int]) -> int:
        seen = set()
        for x in nums:
            if x in seen:
                return x
            seen.add(x)

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Only the answer repeats, so there is no need to count to n.

Interview Explanation
#

Every other value appears once, so the first value seen twice is the answer, found with a set while scanning. Time O(n).

Related

LeetCode 804: Unique Morse Code Words
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 804 note: translate each word into a Morse string and count the distinct results with a set
LeetCode 594: Longest Harmonious Subsequence
·1 min
LeetCode Easy Array Hash-Table Sliding-Window Sorting
LeetCode 594 note: subsequences need not be contiguous, so just count; for each x add the counts of x and x + 1
LeetCode 500: Keyboard Row
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 500 note: make a set for each keyboard row and keep words whose lowercase character set is a subset of one row
LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them
LeetCode 350: Intersection of Two Arrays II
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 note: an intersection keeping multiplicity, where Counter’s & takes the smaller count from each side
LeetCode 929: Unique Email Addresses
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 929 note: split at @, normalize only the local part (drop everything after +, remove dots), rejoin with the domain and collect in a set