You are given an array of unsorted integers between 1 and 1,000,000, however, one number is missing. Write a program to determine which number is missing from the array? Can you solve this in linear runtime?
You are given an array of unsorted integers between 1 and 1,000,000, however, one number is missing. Write a program to determine which number is missing from the array? Can you solve this in linear runtime?
Permalink: http://problemotd.com/problem/the-missing-one/
Content curated by @MaxBurstein
Comments:
Adam - 10 years, 3 months ago
expected_sum = (1 + 1000000) * (500000) array_sum = sum(xs) missing = expected_sum - array_sum
reply permalink
Max Burstein - 10 years, 3 months ago
I like this approach. Good stuff
reply permalink
Karl - 10 years, 3 months ago
Very nice for this problem yes (elegant, even), but what about two missing numbers?
The codified solutions could be easily modified to find both.
reply permalink
Foppe - 10 years, 3 months ago
reply permalink
Beginner - 10 years, 3 months ago
Would anyone care to explain what linear run time is? All the websites I've looked at assume I know too much.
reply permalink
Foppe - 10 years, 3 months ago
Big Oh notation states "how well an algorithm scales as data(ponts) increases". Linear being almost optimal as run-time means you run only one time over the data as shown in my solution above. The array is traversed only once for adding all integers. A less optimal solution (n log n) would start with sorting the array then picking the missing number. You'd need to traverse the array more than once to sort it en then traverse it again to find the missing integer. Optimisation of algorithms is important when dealing with lhuge data-sets. One million integers is relatively not large.
reply permalink
Anonymous - 10 years, 3 months ago
Basically only looking at each number in the array once
reply permalink
wobblebucket - 10 years, 3 months ago
reply permalink