Learner Level
Implement the findDuplicateNumber method that returns a duplicate value from the array.
The input contains an integer array nums and its length size. Your task is to find and return the repeated number in the array.
For example, in [1,3,4,2,2], the number 2 appears more than once, so the answer is 2. If no duplicate exists in a different test case, return -1.
Use a set to track the values that have already been visited.
Scan the array from left to right. If the current number is already present in the set, it means this number has appeared before, so return it immediately.
If the number is not present, add it to the set and continue checking the remaining elements.
Pseudocode:
function findDuplicateNumber(nums, size):
seen = empty set
for i from 0 to size - 1:
if nums[i] exists in seen:
return nums[i]
add nums[i] to seen
return -1