Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Method 1
- '''sum of 1 to n using (n*(n+1))//2 and then subtract the sum of the array, even if all number from 1 to n is there,still answer would be 0 which is right answer'''
- class Solution:
- def missingNumber(self, nums: List[int]) -> int:
- n = len(nums)
- return n * (n + 1) // 2 - sum(nums)
- """
- Intuition:
- The array contains n distinct numbers from the range [0, n], so exactly one number is missing.
- If we XOR all values from 0 to n and also XOR all elements in nums, every number that appears
- will cancel out (because a ^ a = 0). The only value left after all cancellations is the missing
- number. This gives an O(n) time solution using O(1) extra space.
- Trick: initialise the answer with len of the array
- """
- class Solution:
- def missingNumber(self, nums: List[int]) -> int:
- ans=len(nums) #Here ans starts with len(nums) ie. n because if all elements are in the range from o to n-1,then n will be the ans.
- for i,x in enumerate(nums):
- ans=ans^i^x
- return ans
Advertisement
Add Comment
Please, Sign In to add comment