Find the array element whose second occurrence appears earliest

Quick Overview

Given an integer array, return the value whose second occurrence appears at the smallest index, or -1 when every value is unique. It tests a single left-to-right scan with a hash set and a careful reading of what first duplicate means.

Find the array element whose second occurrence appears earliest

Company: Vmware

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

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 ```python 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 ```text 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. ```text Input: nums = [1,2,3,4,5] Output: -1 ``` All elements are unique, so the function returns -1.

Overview: Given an integer array, return the value whose second occurrence appears at the smallest index, or -1 when every value is unique. It tests a single left-to-right scan with a hash set and a careful reading of what first duplicate means.

Vmware logo
Vmware
Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

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.