Find All Duplicates in an Array — LeetCode 442 Python Solution

MediumArrayHash TableSorting
Problem
#442
Pattern
Sorting
Reading time
2 min

The problem

Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears at most twice, return an array of all the integers that appears twice. You must write an algorithm that runs in O(n) time and uses only constant auxiliary space, excluding the space needed to store the output

This statement is abridged. Read the full problem on LeetCode.

Example

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

Python solution

Python
class Solution:
    def findDuplicates(self, nums: List[int]) -> List[int]:
        for i in range(len(nums)):
            while nums[i] != nums[nums[i] - 1]:
                nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]
        return [v for i, v in enumerate(nums) if v != i + 1]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 442. Find All Duplicates in an Array is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 442. Find All Duplicates in an Array?
LeetCode 442. Find All Duplicates in an Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 442. Find All Duplicates in an Array?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 442. Find All Duplicates in an Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 442. Find All Duplicates in an Array cover?
LeetCode 442. Find All Duplicates in an Array is tagged Array, Hash Table and Sorting 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