Set Mismatch
Problem
Given an array nums containing n integers where each integer is in the range [1, n] inclusive, exactly one number is duplicated and one number is missing; return the duplicate number and the missing number as an array [duplicate, missing].
- 2 ≤ nums.length ≤ 10⁴
- 1 ≤ nums[i] ≤ nums.length
Example
nums = [1,2,2,4][2,3]The array should contain numbers 1 through 4. The number 2 appears twice, and the number 3 is missing. The algorithm detects the duplicate by tracking seen numbers and then finds the missing number by checking which number in the range 1 to n was never seen.
Approach
Straightforward Solution
A brute-force approach would check counts of each number using nested loops, resulting in O(n^2) time complexity, which is inefficient for large inputs.
Core Observation
The problem reduces to identifying one number that appears twice and one number missing from the range 1 to n. Tracking occurrences efficiently allows detection of the duplicate and missing numbers.
Path to Optimal
By using a boolean array to track which numbers have been seen, the algorithm can detect the duplicate in a single pass. Then, a second pass over the range 1 to n identifies the missing number by finding which number was never marked as seen. This approach reduces time complexity to O(n) and space complexity to O(n).
Optimal Approach
Create a boolean array of size n+1 initialized to False. Iterate over nums, marking seen[num] as True; if already True, record num as duplicate. Then iterate from 1 to n to find the number not seen, which is the missing number. Return [duplicate, missing].
Time
O(n)
The algorithm makes two passes over arrays of length n: one over the input nums and one over the range 1 to n, each O(n).
Space
O(n)
The boolean array of size n+1 stores presence information for each number, which scales linearly with input size. This auxiliary space is necessary for constant-time membership checks.
Pattern Spotlight
Hash Maps (Boolean Array for Presence Tracking)
When needing to detect duplicates and missing elements within a known range, use a presence-tracking data structure to achieve O(n) time by trading space for constant-time membership checks.
Solution
| 1 | class Solution: |
| 2 | def findErrorNums(self, nums: List[int]) -> List[int]: |
| 3 | n = len(nums) |
| 4 | seen = [False] * (n + 1) |
| 5 | |
| 6 | duplicate = -1 |
| 7 | |
| 8 | for num in nums: |
| 9 | if seen[num]: |
| 10 | duplicate = num |
| 11 | else: |
| 12 | seen[num] = True |
| 13 | |
| 14 | missing = -1 |
| 15 | |
| 16 | for num in range(1, n + 1): |
| 17 | if not seen[num]: |
| 18 | missing = num |
| 19 | break |
| 20 | |
| 21 | return [duplicate, missing] |
Step-by-Step Solution
Track Seen Numbers to Identify the Duplicate
| 3 | n = len(nums) |
| 4 | seen = [False] * (n + 1) |
| 6 | duplicate = -1 |
| 8 | for num in nums: |
| 9 | if seen[num]: |
| 10 | duplicate = num |
| 11 | else: |
| 12 | seen[num] = True |
Objective
To iterate through nums and mark each number as seen, detecting the duplicate when a number is encountered twice.
Key Insight
Using a boolean array indexed by number allows constant-time checks for whether a number has been seen before. When a number is found already marked as seen, it must be the duplicate. This approach avoids nested loops and reduces time complexity from O(n^2) to O(n).
Interview Quick-Check
Core Logic
Mark each number as seen in a boolean array; if already marked, record it as the duplicate.
State & Boundaries
The boolean array size is n+1 to align indices with numbers 1 through n, simplifying indexing.
Common Pitfalls & Bugs
Forgetting to check if a number is already seen before marking it leads to missing the duplicate.
Identify the Missing Number by Checking Unseen Indices
| 14 | missing = -1 |
| 16 | for num in range(1, n + 1): |
| 17 | if not seen[num]: |
| 18 | missing = num |
| 19 | break |
Objective
To find the missing number by scanning the boolean array for the first number not marked as seen.
Key Insight
After marking all seen numbers, the missing number corresponds to the index in the boolean array that remains False. This direct scan leverages the problem's guarantee that exactly one number is missing, allowing an immediate break upon discovery.
Interview Quick-Check
Core Logic
Scan from 1 to n to find the first number not marked as seen, which is the missing number.
State & Boundaries
Break immediately upon finding the missing number to avoid unnecessary iterations.
Common Pitfalls & Bugs
Failing to break early can cause unnecessary computation, though it doesn't affect correctness.
Return the Result Array Containing Duplicate and Missing Numbers
| 21 | return [duplicate, missing] |
Objective
To return the final answer as an array containing the duplicate and missing numbers.
Key Insight
Returning the result in the specified format completes the problem requirements. This step is straightforward but essential for correctness.
Interview Quick-Check
Core Logic
Return the array [duplicate, missing] as the problem requires.
Line Analysis
This solution has 2 Critical lines interviewers watch for.
if seen[num]:
Check if the current number has already been seen.
Detecting a previously seen number here is the definitive check that identifies the duplicate, enabling immediate recording without further search.
if not seen[num]:
Check if the current number in the range was not seen.
Identifying the missing number here is the critical step that completes the problem's requirement, leveraging the presence tracking.
seen = [False] * (n + 1)
Initialize a boolean array seen of size n+1 with all False values.
This array tracks which numbers from 1 to n have been encountered, enabling O(1) membership checks and efficient duplicate detection.
seen[num] = True
Mark the current number as seen in the boolean array.
This update is essential to track presence and enable duplicate detection in subsequent iterations.
return [duplicate, missing]
Return the array containing the duplicate and missing numbers.
Returning the result in the specified format completes the problem solution and satisfies the output requirements.
for num in nums:
Iterate over each number in nums to detect duplicates.
This loop processes every element to check for repeated occurrences, the core step for identifying the duplicate number.
duplicate = num
Assign the current number to duplicate upon detection.
Recording the duplicate number at this point captures the problem's key anomaly for later return.
for num in range(1, n + 1):
Iterate over the range 1 to n inclusive to find the missing number.
This loop scans all possible numbers to identify which one was never seen, fulfilling the problem's missing number requirement.
missing = num
Assign the current number as the missing number.
Recording the missing number allows the algorithm to return the correct result.
else:
Else clause for marking a number as seen for the first time.
This branch ensures that numbers are tracked correctly, preventing false duplicate detection.
break
Break the loop after finding the missing number.
Early termination avoids unnecessary iterations once the missing number is found, improving efficiency.
n = len(nums)
Calculate the length of the input array nums.
Knowing the length n is essential to create a presence tracking array sized n+1, aligning indices with the problem's number range.
duplicate = -1
Initialize duplicate variable to -1 as a placeholder.
Setting duplicate to -1 prepares to store the detected duplicate number once found, ensuring a defined state before iteration.
missing = -1
Initialize missing variable to -1 as a placeholder.
Preparing missing to store the absent number ensures a defined state before searching.
Test Your Understanding
Why is a boolean array used instead of a hash set, and why is it sufficient for this problem?
Because the numbers are guaranteed to be in the range 1 to n, a boolean array indexed by number provides O(1) presence checks with less overhead than a hash set. This leverages the problem's constraints for efficient membership tracking.
Related Problems
Hash Maps pattern
Don't just read it. Drill it.
Reconstruct Set Mismatch from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Set Mismatch drill