First Duplicate Encounter
Problem statement
Scan nums from left to right and return the first value encountered for a second time. Return -1 if no value repeats. First refers to the smallest second-occurrence index, not the smallest value or earliest first occurrence. You may temporarily modify the array, but must restore all its original values before returning. Aim for linear time and constant additional space.
Function
firstDuplicate(nums: int[]) → intExamples
Example 1
nums = [2,1,3,3,2]return = 3The second 3 occurs at index 3, earlier than the second 2 at index 4.
Example 2
nums = [1,2,3]return = -1Every value appears only once.
Constraints
0 <= nums.length <= 2000.1 <= nums[i] <= 2000.- Every value is at most nums.length.