#645
Set Mismatch
EasyArrayHash TableBit ManipulationSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages mathematical properties to find the duplicate and missing numbers in linear time. By using a single pass and simple arithmetic, we can achieve better performance.
⚙️
Algorithm
5 steps- 1Step 1: Create a set to track numbers seen so far.
- 2Step 2: Iterate through the array to find the duplicate number.
- 3Step 3: Calculate the expected sum of numbers from 1 to n using the formula n*(n+1)/2.
- 4Step 4: Calculate the actual sum of the numbers in the set.
- 5Step 5: The missing number is the difference between the expected sum and the actual sum.
solution.py13 lines
1def findErrorNums(nums):
2 seen = set()
3 duplicate = -1
4 total = 0
5 n = len(nums)
6 expected_sum = n * (n + 1) // 2
7 for num in nums:
8 if num in seen:
9 duplicate = num
10 seen.add(num)
11 total += num
12 missing = expected_sum - (total - duplicate)
13 return [duplicate, missing]ℹ
Complexity note: The time complexity is O(n) because we traverse the array only once. The space complexity is O(n) due to the additional set used to track seen numbers.
- 1The sum of the first n natural numbers can be used to find the missing number.
- 2Using a set allows for O(1) average time complexity for lookups.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.