medium +25 pts

Two Missing Numbers

Find the two missing integers from a shuffled sequence with unique values.

You are given a list `nums` containing exactly `n - 2` unique integers, each in the range `1` to `n`. Two numbers from that range are missing. Write a function `find_missing_numbers(nums)` that returns a list of the two missing numbers in ascending order. For example, if `n = 5` and `nums = [3, 1, 4]`, the missing numbers are `2` and `5`, so the function returns `[2, 5]`. You do **not** need to compute `n` from the length of `nums`; the function will receive `nums` only. However, you can determine `n` by noting that `n = len(nums) + 2` (since exactly two numbers are missing). The input list may be in any order. Implement the function in Python. Your solution should be efficient in both time and space.

Constraints

- `nums` contains only integers. - All integers in `nums` are unique and in the range `[1, n]`. - `len(nums) >= 2` (so `n >= 4`). - The input list is not necessarily sorted. - Expected time complexity: O(n), expected auxiliary space: O(1) (excluding input/output).

Example

>>> find_missing_numbers([3, 1, 4])
[2, 5]
>>> find_missing_numbers([1, 2, 3, 4])
[5, 6]
>>> find_missing_numbers([4, 2, 3])
[1, 5]
25 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Let n = len(nums) + 2. The sum of all numbers from 1 to n minus the sum of nums gives the sum of the two missing numbers.
Use the sum of squares to get another equation involving the missing numbers.
If the two missing numbers are a and b, then you know a + b and a² + b². Solve the system to get a and b.
Alternatively, use a set of all numbers from 1 to n and subtract the set of nums — but that uses O(n) space, which is acceptable if you can't derive the math.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.