Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
A duplicate is recognized when its value appears for a second time. Since exactly two values occur twice and all others occur once, remembering previously seen values identifies the two extra occurrences directly.
Approach
Initialize an empty set and an empty result list. Scan nums in order. If the current value is already in the set, append it to the result. Otherwise insert it into the set.
Return the result after the scan. The first occurrence of each value only records its presence, while the second occurrence reports it. The stated frequency guarantees mean the result contains exactly the two required values, each once; their discovery order is acceptable because the answer may be returned in any order.
class Solution:
def getSneakyNumbers(self, nums: List[int]) -> List[int]:
seen = set()
res = []
for x in nums:
if x in seen:
res.append(x)
else:
seen.add(x)
return resComplexity analysis
Let n = nums.length. Time: O(n). Auxiliary space: O(n) for the seen set, excluding the constant-size returned duplicates.
