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.

Example 1

Input
nums (int[]) = [1,3,4,2,2]
size (int) = 5
Returns (int) 2

Example 2

Input
nums (int[]) = [3,1,3,4,2]
size (int) = 5
Returns (int) 3

Example 3

Input
nums (int[]) = [1,1]
size (int) = 2
Returns (int) 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
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.