One-liner solution in Python

  • 0
    class Solution(object):
        def missingNumber(self, nums):
            return ((1 + len(nums)) * (len(nums)) / 2) - sum(nums)

  • 0

    Yes, as there is a built-in sum function in python, just one line is enough. For other languages without sum functions, e.g. c, c++, etc. I am afraid that one line is impossible.

  • 0

    How does this work for inputs like '[1]' where the 'missing number' is 0. Also, I've been seeing that if there aren't actually missing numbers, LeetCode expects the 'missing number' to be n+1, e.g. if the input is [0, 1, 2, 3], the missing number should be 4

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.