imashutosh51

Missing number

Feb 4th, 2026 (edited)
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.03 KB | None | 0 0
  1. #Method 1
  2. '''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'''
  3. class Solution:
  4.     def missingNumber(self, nums: List[int]) -> int:
  5.         n = len(nums)
  6.         return n * (n + 1) // 2 - sum(nums)
  7.  
  8.  
  9.  
  10. """
  11. Intuition:
  12. The array contains n distinct numbers from the range [0, n], so exactly one number is missing.
  13. If we XOR all values from 0 to n and also XOR all elements in nums, every number that appears
  14. will cancel out (because a ^ a = 0). The only value left after all cancellations is the missing
  15. number. This gives an O(n) time solution using O(1) extra space.
  16.  
  17. Trick: initialise the answer with len of the array
  18. """
  19.  
  20.  
  21. class Solution:
  22.     def missingNumber(self, nums: List[int]) -> int:
  23.         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.
  24.         for i,x in enumerate(nums):
  25.             ans=ans^i^x
  26.         return ans
  27.        
Advertisement
Add Comment
Please, Sign In to add comment