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.
1#include <iostream>
2#include <vector>
3using namespace std;
4
5int missingNumber(vector<int>& nums) {
6 int n = nums.size();
7 int total = n * (n + 1) / 2;
8 int sum = 0;
9 for (int num : nums) {
10 sum += num;
11 }
12 return total - sum;
13}
14
15int main() {
16 vector<int> nums = {3, 0, 1};
17 cout << "Missing number: " << missingNumber(nums) << endl;
18 return 0;
19}
This C++ solution uses the same logic as the C solution. It iterates over the vector, sums up the elements, and subtracts this sum from the expected total sum to find 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.
1using System;
2
3public class Solution {
4 public int MissingNumber(int[] nums) {
5 int xorResult = 0;
6 for (int i = 0; i < nums.Length; i++) {
7 xorResult ^= i ^ nums[i];
8 }
9 xorResult ^= nums.Length;
10 return xorResult;
11 }
12
13 public static void Main(string[] args) {
14 int[] nums = {3, 0, 1};
15 Solution sol = new Solution();
16 Console.WriteLine("Missing number: " + sol.MissingNumber(nums));
17 }
18}
This C# program leverages XOR properties to find the missing element by processing indices and numbers simultaneously.