Given an array of integers 1 to 100 (inserted randomly), and one integer is taken out of the array. What is the most efficient way of finding the integer that is missing?
-
3possible duplicate of Quickest way to find missing number in an array of numbersbaci– baci2014-01-12 21:46:08 +00:00Commented Jan 12, 2014 at 21:46
-
At 2.8k rep, one would kind of expect a user to know to show proof of a bit of research done in a question...Bernhard Barker– Bernhard Barker2014-01-12 23:14:54 +00:00Commented Jan 12, 2014 at 23:14
Add a comment
|
2 Answers
As you know the integers, make a sum of all of them:
(1+N)*N/2 = (1+100)*100/2 = 5050
And now substract the sum of those that are in the array (S'). The difference will be the one missing number you seek (so x = 5050 - S').
Time complexity is O(N) and can't be solved faster, because you definitely need to read the array once.
2 Comments
Aseem Goyal
this is probably not optimal answer , considering N is very large , so you can have an overflow.
Martin Zikmund
It is optimal, because we are talking about 1..100 range here. In case we got larger nunmbers, we still could use this but implement our own integer class for large integers based on arrays.
MZetko already answer the basic case but here are 4 other solutions to this where the array can be sorted or unsorted
4 Comments
Bernhard Barker
Rather than just providing a link, it would be preferable to include the essential parts of the answer here, and just provide the link for additional reference. If you're not up to this task, you should consider simply leaving a comment on the question instead of posting an answer.
Kartik
Will keep that in mind the next time, but in my defense, I wrote the answer in the link
Bernhard Barker
Remember that posts are here for the long haul - don't just write new posts to conform to guidelines, but also edit existing ones (i.e. this post).
Yaobin Then
What's worse when the link is now a 404