Find the Duplicate Number — LeetCode 287 Python Solution

MediumBit ManipulationArrayTwo PointersBinary Search
Problem
#287
Reading time
2 min

The problem

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number.

Example

Input
nums = [1,3,4,2,2]
Output
2

Python solution

Python
class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        def f(x: int) -> bool:
            return sum(v <= x for v in nums) > x

        return bisect_left(range(len(nums)), True, key=f)

Complexity

MeasureComplexity
TimeO(n \times \log n), where n is the length of the array nums
SpaceO(1) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 287. Find the Duplicate Number is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On a study list

This problem is on NeetCode 150.

Frequently asked questions

How hard is LeetCode 287. Find the Duplicate Number?
LeetCode 287. Find the Duplicate Number is rated Medium on LeetCode.
What is the time complexity of LeetCode 287. Find the Duplicate Number?
The Python solution on this page runs in O(n \times \log n), where n is the length of the array nums.
What is the space complexity of LeetCode 287. Find the Duplicate Number?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 287. Find the Duplicate Number cover?
LeetCode 287. Find the Duplicate Number is tagged Bit Manipulation, Array, Two Pointers and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview