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 ]
Difficulty
and has an acceptance rate of about 45% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Bit Manipulation
- Hash Table
- Sorting
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 287: Find the Duplicate Number
Solved On The Same Day
- problem 112: Path Sum
- problem 409: Longest Palindrome
- problem 717: 1-bit and 2-bit Characters
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 16: 3Sum Closest
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 114: Flatten Binary Tree to Linked List
- problem 116: Populating Next Right Pointers in Each Node
- problem 129: Sum Root to Leaf Numbers
- problem 131: Palindrome Partitioning
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 165: Compare Version Numbers
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 539: Minimum Time Difference
- problem 583: Delete Operation for Two Strings
- problem 633: Sum of Square Numbers
- problem 648: Replace Words
- problem 650: 2 Keys Keyboard
- problem 670: Maximum Swap
- problem 786: K-th Smallest Prime Fraction
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
Extra
- 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