Set Mismatch — LeetCode 645 Python Solution

EasyBit ManipulationArrayHash TableSorting
Problem
#645
Reading time
2 min

The problem

You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.

Example

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

Python solution

Python
from typing import List

def findErrorNums(nums: List[int]) -> List[int]:
    n = len(nums)
    seen = set()
    dup = -1
    for x in nums:
        if x in seen:
            dup = x
        else:
            seen.add(x)
    missing = next(i for i in range(1, n + 1) if i not in seen)
    return [dup, missing]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the array nums auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 645. Set Mismatch is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

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

Related problems

Frequently asked questions

How hard is LeetCode 645. Set Mismatch?
LeetCode 645. Set Mismatch is rated Easy on LeetCode.
What is the time complexity of LeetCode 645. Set Mismatch?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 645. Set Mismatch?
The Python solution on this page uses O(n), where n is the length of the array nums auxiliary space.
What topics does LeetCode 645. Set Mismatch cover?
LeetCode 645. Set Mismatch is tagged Bit Manipulation, 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