Find the Duplicate Number — LeetCode 287 Python Solution
- Problem
- #287
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n), where n is the length of the array nums |
| Space | O(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.