missing_number

 1# @leet start
 2class Solution:
 3    def missingNumber(self, nums: list[int]) -> int:
 4        """
 5        This question gives a set of numbers from [0..n] where one number is missing.
 6        We could figure out the missing number by putting all items in a set,
 7        and iterating from [0..n] to find the missing number. This is $O(n)$ time
 8        and space.
 9
10        We can do better by exploiting the fact that the sum of [0..n] can be calculated
11        with the formula $n * (n - 1) / 2$.
12
13        Thus, this takes no extra time.
14        """
15        n = len(nums) + 1
16        total = n * (n - 1) // 2
17        return total - sum(nums)
18
19
20# @leet end
21sol = Solution()
22
23
24def test():
25    assert sol.missingNumber([3, 0, 1]) == 2
26    assert sol.missingNumber([0, 1]) == 2
27    assert sol.missingNumber([9, 6, 4, 2, 3, 5, 7, 0, 1]) == 8
class Solution:
 3class Solution:
 4    def missingNumber(self, nums: list[int]) -> int:
 5        """
 6        This question gives a set of numbers from [0..n] where one number is missing.
 7        We could figure out the missing number by putting all items in a set,
 8        and iterating from [0..n] to find the missing number. This is $O(n)$ time
 9        and space.
10
11        We can do better by exploiting the fact that the sum of [0..n] can be calculated
12        with the formula $n * (n - 1) / 2$.
13
14        Thus, this takes no extra time.
15        """
16        n = len(nums) + 1
17        total = n * (n - 1) // 2
18        return total - sum(nums)
def missingNumber(self, nums: list[int]) -> int:
 4    def missingNumber(self, nums: list[int]) -> int:
 5        """
 6        This question gives a set of numbers from [0..n] where one number is missing.
 7        We could figure out the missing number by putting all items in a set,
 8        and iterating from [0..n] to find the missing number. This is $O(n)$ time
 9        and space.
10
11        We can do better by exploiting the fact that the sum of [0..n] can be calculated
12        with the formula $n * (n - 1) / 2$.
13
14        Thus, this takes no extra time.
15        """
16        n = len(nums) + 1
17        total = n * (n - 1) // 2
18        return total - sum(nums)

This question gives a set of numbers from [0..n] where one number is missing. We could figure out the missing number by putting all items in a set, and iterating from [0..n] to find the missing number. This is $O(n)$ time and space.

We can do better by exploiting the fact that the sum of [0..n] can be calculated with the formula $n * (n - 1) / 2$.

Thus, this takes no extra time.

sol = <Solution object>
def test():
25def test():
26    assert sol.missingNumber([3, 0, 1]) == 2
27    assert sol.missingNumber([0, 1]) == 2
28    assert sol.missingNumber([9, 6, 4, 2, 3, 5, 7, 0, 1]) == 8