File: set-mismatch/solution.py

Date: 2026-06-06

Time: 19:03

set-mismatch/solution.py

Purpose

This file solves LeetCode 645 - Set Mismatch. Given an array that should contain integers 1 through n exactly once, but where one number was duplicated (replacing another), it identifies which number is duplicated and which is missing. Returns [duplicate, missing].

Key Components

Solution.findErrorNums(self, nums: List[int]) -> List[int] — The sole method. Takes a corrupted 1-to-n sequence and returns the duplicate and missing numbers as a two-element list.

Flow

The algorithm uses two passes with a mathematical finish:

1. Find the duplicate (lines 12-16): Iterates through nums, tracking seen values in a set. The first number already in seen is the duplicate.

2. Find the missing via sum arithmetic (lines 17-19): The expected sum of 1..n is n*(n+1)//2. The actual sum differs from expected by exactly missing - duplicate (since one copy of missing was replaced by an extra copy of duplicate). Rearranging: missing = expectedsum - actualsum + duplicate.

Patterns

Dependencies

Invariants

Error Handling

None. The code assumes valid input per LeetCode constraints. If no duplicate exists, duplicate stays -1 and the returned missing value will be wrong — but this can't happen under the problem's guarantees.

Complexity