Problem 645

Abstract / Summary

A set of numbers from one to n has one number duplicated and another missing find both numbers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0645.py

class Solution:
    def findErrorNums(self, nums: List[int]) -> List[int]:
        nums.sort()

        i = 1
        while nums[i-1] == i: # zero-indexed
            i += 1

        j = i
        while j <= len(nums) and nums[j-1] != j:
            j += 1

        if nums[i-1] < i:
            return [ i-1, j-1 ]
        else:
            return [ j, i ]
16 lines | 374 bytes | submitted August 15, 2023 | GitHub   7% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • Hash Table
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The Solution.findErrorNums method receives a list of integers that should contain every value from 1 to n exactly once, but one value appears twice while another is missing. The routine returns a two-element list where the first element is the duplicated number and the second element is the missing number. The implementation follows a three-phase approach: it first orders the input, then locates the first position where the sorted sequence diverges from the expected natural order, proceeds to locate the second divergence, and finally decides which of the two discovered indices corresponds to the duplicate and which to the missing value.

Sorting the input

The algorithm begins by arranging the numbers in non-decreasing order. This step enables a direct comparison between the value at each index and the index-based expectation (i + 1).

nums.sort()

Sorting is performed in-place, which avoids allocating an auxiliary array and therefore reduces memory pressure. The built-in sort uses an adaptive, stable algorithm that runs efficiently on partially ordered data, providing a practical performance benefit when the input is nearly sorted.

Scanning for the first mismatch

After sorting, the code walks forward from the start of the list, checking whether each element matches its 1-based position. The loop stops as soon as it encounters a discrepancy, leaving i positioned at the first index where the sorted value does not equal the expected count.

i = 1
while nums[i-1] == i:   # zero-indexed
    i += 1

Because the loop increments i only while the condition holds, it terminates early in the common case where the duplicate appears early in the sequence. This early-exit behavior limits the number of comparisons needed.

Scanning for the second mismatch

Having identified the first divergent index, the routine continues scanning from that point to locate the second position where the sorted value fails to match its expected count. The variable j starts at i and advances until either the end of the list is reached or a matching condition is found.

j = i
while j <= len(nums) and nums[j-1] != j:
    j += 1

The loop condition includes a boundary check (j <= len(nums)) to safely handle the scenario where the missing number is n (the largest possible value). By reusing the same index variable range, the algorithm avoids a second full pass over the array.

Determining duplicate and missing values

At this stage, i points to the first index where the sorted value is out of place, and j points to the second such index (or to len(nums) + 1 when the missing number is beyond the array bounds). The final decision hinges on whether the element at i-1 is smaller than its expected value i. If it is smaller, the element at i-1 must be the duplicated number, and the element at j-1 (or the implied missing value) is the absent number. Otherwise, the roles are reversed.

if nums[i-1] < i:
    return [ i-1, j-1 ]
else:
    return [ j, i ]

The conditional logic directly maps the relative ordering of the mismatched element to the correct output ordering, eliminating the need for additional arithmetic or look-ups.

Edge-case handling

The implementation gracefully manages several boundary conditions without extra code paths. When the duplicate occurs at the very beginning of the list, the first while loop exits immediately, leaving i equal to 1. When the missing number is the largest value n, the second while loop runs until j exceeds the length of the list, and the return expression uses j-1 (which becomes n) to represent the missing element. If the duplicate is larger than the missing number, the final else branch correctly swaps the positions, ensuring the duplicate is always reported first. The use of zero-based indexing (nums[i-1]) combined with 1-based expectations (i) maintains consistency across all possible input permutations.

Performance optimizations

The code leverages in-place sorting to keep auxiliary memory usage low. Both scanning phases are linear and stop as soon as the required information is found, avoiding unnecessary traversal of the entire array. The second scan starts from the point where the first scan stopped, which reduces the total number of element accesses compared with restarting from the beginning. The conditional return avoids extra calculations by directly using the indices that have already been computed. Together, these choices produce a solution that is both memory-efficient and fast for typical input sizes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a row of numbered blocks, but some of them got mixed up and one is missing while another one is doubled up. This code acts like a little detective that wants to fix the line. First, the code sorts all the blocks in order from smallest to biggest so they are easy to look at. Then, the code walks down the line looking for the first spot where the number on the block does not match its position. Once that spot is found, the code keeps looking to see which number is repeated and which number is missing. It behaves like a scavenger hunt where the goal is to pinpoint exactly which block is extra and which one should be tucked into the empty space.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 4 | μ = 4.81 | σ = 1.85

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
muhammadfarhankt Go
pruthvikp Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
muhammadfarhankt Go
pruthvikp Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
44 links | 30 authors | 10 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   August 15, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality