Missing Number If the array contains numbers from 1 to N with one missing element, you can solve it in multiple ways.
Example
int[] a = { 1, 2, 4, 5 };
Output
Missing Number = 3
Approach 1: Sum Formula (Best - O(n))
using System;
class Program
{
static void Main()
{
int[] a = { 1, 2, 4, 5 };
int n = a.Length + 1;
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
foreach (int num in a)
{
actualSum += num;
}
Console.WriteLine("Missing Number = " + (expectedSum - actualSum));
}
}
Output
Missing Number = 3
Complexity
- Time: O(n)
- Space: O(1)
No comments:
Post a Comment