FastPrepFind the Duplicate Number

Find the Duplicate Number

Walmart Labs logoWalmart Labs● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

You are given an integer array nums of length n + 1. Every value is in 1..n. Exactly one distinct value occurs more than once; it may occur more than twice. Return that value.

For this exercise, assume the conventional duplicate-number contract: do not modify the array, and aim for O(n) time and O(1) auxiliary space. The report names a variant without describing its changed rule, so this exercise uses the standard core.

Function

findDuplicate(nums: int[]) → int

Examples

Example 1

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

Cycle entry differs from first value.

Example 2

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

Cycle-entry duplicate near the start.

Example 3

nums = [1,1]return = 1

Minimum n equals one.

Constraints

  • 1 <= n <= 1000.
  • nums.length = n + 1 and 1 <= nums[i] <= n.
  • Exactly one distinct value is repeated; all other values occur at most once.

More Walmart Labs problems

See Walmart Labs hiring insights
public int findDuplicate(int[] nums) {
    // Write your code here.
}
nums[1,3,4,2,2]
expected2
Checking account…