1

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?

2

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

this is probably not optimal answer , considering N is very large , so you can have an overflow.
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.
3

MZetko already answer the basic case but here are 4 other solutions to this where the array can be sorted or unsorted

https://github.com/KartikTalwar/Algorithms/blob/master/Arrays/Find%20only%201%20missing%20number%20from%20an%20array/Find1MissingElementFromArray.py

4 Comments

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.
Will keep that in mind the next time, but in my defense, I wrote the answer in the link
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).
What's worse when the link is now a 404

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.