LeetCode 268. Missing Number

Description

https://leetcode.com/problems/missing-number/

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

Example 1:

Input: [3,0,1]
Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

Explanation

use a hashmap to help check which number is missing

Python Solution

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        
        n = len(nums)
        
        visited = set()
        
        for num in nums:
            visited.add(num)
        
        for i in range(0, n + 1):
            if i not in visited:
                return i
        
  • Time complexity: O(N).
  • Space complexity: O(1).

One Thought to “LeetCode 268. Missing Number”

Leave a Reply

Your email address will not be published. Required fields are marked *