Insert values into a set and return the first duplicate; all other values occur once, so the duplicate must be the repeated element.
Complexity
O(n) time and O(n) space.
Find the single value repeated n times in an array of size two n.
Insert values into a set and return the first duplicate; all other values occur once, so the duplicate must be the repeated element.
O(n) time and O(n) space.
package main
func repeatedNTimes(nums []int) int {
seen := map[int]bool{}
for _, value := range nums {
if seen[value] {
return value
}
seen[value] = true
}
panic("input must contain a repeated element")
}
class Solution:
def repeatedNTimes(self, nums: list[int]) -> int:
seen: set[int] = set()
for value in nums:
if value in seen: return value
seen.add(value)
raise ValueError("input must contain a repeated element")
function repeatedNTimes(nums: number[]): number {
const seen = new Set<number>();
for (const value of nums) { if (seen.has(value)) return value; seen.add(value); }
throw new Error("Input must contain a repeated element");
}