Given an array of integers nums, return the first duplicate element, defined as the element whose second occurrence appears earliest in the array.
If no element appears more than once, return -1.
Formally, among all indices j such that nums[j] == nums[i] for some i < j, find the smallest such j and return nums[j].
Function Signature
def first_duplicate(nums: list[int]) -> int:
Rules
-
Return the value, not its index.
-
Values can be negative, including
-1
. If
-1
is the first duplicate, the function returns
-1
, the same value it returns when there is no duplicate.
Constraints
-
1 <= nums.length <= 10^5
-
-10^9 <= nums[i] <= 10^9
Examples
Input: nums = [2,1,3,5,3,2]
Output: 3
The value 3 has its second occurrence at index 4, while 2 has its second occurrence at index 5. Index 4 comes first, so the answer is 3, even though 2 appears earlier in the array.
Input: nums = [1,2,3,4,5]
Output: -1
All elements are unique, so the function returns -1.