Algorithm.
step 1: store the sequence in the array
step 2: calculate the sum of array;
step: 3: calculate sum of 'n' numbers from 1 to n using the formula n*(n+1)/2;
step 4 : subtract sum of array from sum of n numbers;
ie (n*(n+1)/2)-sum of array;
step 5: the difference is the missing number
this approach is better when there is a single missing number...then what about when there are 2 missing numbers...
its very simple
for the numbers in a sequence the difference will be 1 for every pair
so find the difference for every pair starting from index 0
when the difference is greater than 1 then the ( minimum number in pair+1) is the missing number
thus we can find more than 1 numbers those are missed from the sequence.
step 1: store the sequence in the array
step 2: calculate the sum of array;
step: 3: calculate sum of 'n' numbers from 1 to n using the formula n*(n+1)/2;
step 4 : subtract sum of array from sum of n numbers;
ie (n*(n+1)/2)-sum of array;
step 5: the difference is the missing number
this approach is better when there is a single missing number...then what about when there are 2 missing numbers...
its very simple
for the numbers in a sequence the difference will be 1 for every pair
so find the difference for every pair starting from index 0
when the difference is greater than 1 then the ( minimum number in pair+1) is the missing number
thus we can find more than 1 numbers those are missed from the sequence.
No comments:
Post a Comment