Learner Level

Implement the findFirstRepeatedValue method that returns the first value that appears more than once while scanning the array.

The input contains an integer array nums and its length size. Your task is to return the first value that appears again while reading the array from left to right.

If no value is repeated, return -1. For example, in [3,5,2,5,3], the value 5 is the first value whose second occurrence is found.

Example 1
Input:
nums (int[]) = [3,5,2,5,3]
size (int) = 5
Return:
(int) 5
Example 2
Input:
nums (int[]) = [1,2,3]
size (int) = 3
Return:
(int) -1
Example 3
Input:
nums (int[]) = [7,7,8]
size (int) = 3
Return:
(int) 7

Use a set to store values that have already appeared.

Scan the array from left to right. If the current value is already in the set, return it immediately because it is the first repeated value encountered. Otherwise, add it to the set.

Pseudocode:

function findFirstRepeatedValue(nums, size):
    seen = empty set
    for each value in nums:
        if value exists in seen:
            return value
        add value to seen
    return -1
Run your code to see the result.