shriyanshi24jindal

Missing Number

Mar 30th, 2026
25
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 4.29 KB | None | 0 0
  1. class Solution {
  2. // approach: sum of n-natural numbers
  3. public int missingNumber(int[] nums) {
  4. int n = nums.length;
  5. int sum1 = (n*(n+1))/2;
  6.  
  7. int sum2 = 0;
  8. for(int ele : nums)
  9. sum2 += ele;
  10.  
  11. return sum1 - sum2;
  12. }
  13. // approach: XOR (a^a = 0)
  14. public int missingNumber(int[] nums) {
  15. int n = nums.length;
  16. int xor1 = 0;
  17. for(int i=1; i<=n; i++)
  18. {
  19. xor1 = xor1 ^ i;
  20. }
  21. int xor2 = 0;
  22. for(int ele : nums)
  23. {
  24. xor2 = xor2 ^ ele;
  25. }
  26. return xor1 ^ xor2;
  27. }
  28. }
RAW Paste Data Copied