FastPrepFirst Duplicate Encounter
Problems/First Duplicate Encounter

First Duplicate Encounter

AMD logoAMD● MediumFULLTIMEONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The source requests first duplicate in O(n) time/O(1) space without supplying a domain. This exercise authors values1..n, earliest-second semantics and temporary-mutation/restoration permission; approximate source match 75%.

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[]) → int

Examples

Example 1

nums = [2,1,3,3,2]return = 3

The second 3 occurs at index 3, earlier than the second 2 at index 4.

Example 2

nums = [1,2,3]return = -1

Every value appears only once.

Constraints

  • 0 <= nums.length <= 2000.
  • 1 <= nums[i] <= 2000.
  • Every value is at most nums.length.

More AMD problems

  • Insert After a Linked-List NodeONSITE INTERVIEW · Seen Oct 2026
  • LRU CacheONSITE INTERVIEW · Seen Oct 2026
  • Lowest Common Ancestor of a Binary TreePHONE SCREEN · Seen Oct 2026
All AMD interview questionsSee AMD hiring insights
Saved
public int firstDuplicate(int[] nums) {
    // Write your code here.
}
Checking account…