287. Find the Duplicate Number

by

Duct Tape Programmer


Question

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Note:
You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.

Quick Hints

  • Binary search on values of array
  • Linkedlist cycle detection

Solution

Approach 1:
  • This approach runs a binary search between 1 and n
Approach 1:
  • This approach models the problem as linkedlist and detects cycle entry point

Time complexity

Approach 1:

O (n log n)

Approach 2:

O (n)

Space complexity

Approach 1:

O (1)

Approach 2:

O (1)

Notes

comments powered by Disqus