This approach uses the formula for the sum of the first n natural numbers: Sum = n * (n + 1) / 2
. By calculating the sum of the numbers from the array and subtracting it from the expected sum, we can find the missing number.
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(1), as no additional space is used beyond variables.
1class Solution {
2 public int missingNumber(int[] nums) {
3 int n = nums.length;
4 int total = n * (n + 1) / 2;
5 int sum = 0;
6 for (int num : nums) {
7 sum += num;
8 }
9 return total - sum;
10 }
11
12 public static void main(String[] args) {
13 Solution sol = new Solution();
14 int[] nums = {3, 0, 1};
15 System.out.println("Missing number: " + sol.missingNumber(nums));
16 }
17}
In this Java solution, we calculate the expected sum using the formula and then find the sum of the array. The difference between these sums gives the missing number.
An efficient approach is using XOR. XORing a number with itself results in zero (n ^ n = 0), and XOR of any number with zero keeps the number unchanged (n ^ 0 = n). By XORing all indices and array elements together, each number present in both will cancel out, leaving the missing number.
Time Complexity: O(n), iterating through the array.
Space Complexity: O(1), using constant space.
1class Solution {
2 public int missingNumber(int[] nums) {
3 int xorResult = 0;
4 for (int i = 0; i < nums.length; i++) {
5 xorResult ^= i ^ nums[i];
6 }
7 xorResult ^= nums.length;
8 return xorResult;
9 }
10
11 public static void main(String[] args) {
12 Solution sol = new Solution();
13 int[] nums = {3, 0, 1};
14 System.out.println("Missing number: " + sol.missingNumber(nums));
15 }
16}
Java solution employs bit manipulation with XOR to successfully find the missing element without extra space, performing operations in O(n) time.