Find the First Value Repeated During a Left-to-Right Scan
Company: Microsoft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Find the earliest repeated value in scan order, then analyze sorted-input and no-built-in-set variants without losing the original ordering rule.
Read the full Microsoft Software Engineer interview experience this question came from
Constraints
- 0 <= len(values) <= 200000.
- Each value is a signed 32-bit integer in [-2147483648, 2147483647].
- Return the value whose second occurrence is earliest in the original left-to-right order.
- Return -1 if no duplicate exists; -1 is also a legal input and duplicate value.
- Do not reorder the primary-task input. Already-sorted and no-built-in-set variants are explanatory follow-ups.
Examples
Input: ([2, 1, 3, 1, 2],)
Expected Output: 1
Explanation: The second 1 is encountered before the second 2, as in the source example.
Input: ([4, 7, 9],)
Expected Output: -1
Explanation: Every element in the second source example is distinct.
Hints
- The relevant ordering is the position of the second occurrence in the unchanged input.