Tuesday, May 13, 2008

Arrays!

Given an array of size N that contains values between 1 and N-1, find the duplicate element(assuming there is only one)?.
Solution:

a) Count all the numbers in the array. call it ActualSumb) Find the sum of first N-1 natural numbers from 1 to N-1. The formula is N*(N+1)/2. Call it TotalSum.c) The answer is Actual Sum - Total Sum
Example:Array : {3, 4, 1, 3, 2}

Actual Sum: 13
Total Sum : 10 (Here, N =5, N-1 = 4, thus Total Sum =(5*4)/2 = 10)Result : 13 - 10 = 3
Time Complexity = 0(n)


If it contains values between 1 and N+1, how would you find the missing element (again assuming there is only one missing)?
Solution:

a) Count all the numbers in the array. call it ActualSum

b) Find the sum of first N+1 natural numbers from 1 to N+1. The formula is N*(N+1)/2. Call it TotalSum.

c) The answer is Total Sum - Actual Sum
Example:Array : {3, 6, 1, 5, 2}

Actual Sum: 17
Total Sum : 21 (Here, N+1 = 6, thus Total Sum =(7*6)/2 = 21)
Result : 21 - 17 = 4
Time Complexity = 0(n)

No comments: