+ 5

How do you find the missing number in a given integer array of 1 to 100 in c?

3rd May 2019, 10:12 AM
Bubbly🎀🎀🎀
Bubbly🎀🎀🎀 - avatar
9 Respostas
+ 12
There's a really cool algortihm for that. It's so simple that you wonder how you didn't think of it, but you'd just never think of it on your own. First, take the sum of all numbers from 1 to 100, I think that's 5050. Then you run through the array and keep subtracting. Whatever is leftover is your missing number :)
3rd May 2019, 3:26 PM
Schindlabua
Schindlabua - avatar
+ 6
Maneren That only works if the array is sorted though 👆
3rd May 2019, 12:00 PM
Anna
Anna - avatar
+ 5
I'd probably make an array of 100 bools (or ints in C) and set them all to false/0 by default. Then iterate over the integer array once and for every number in the array set the according element in the bool array to true/1. Then iterate over the bool array and check which value is false/0. Might not be the most efficient solution, but it's probably still better than anything that needs 100*100 = 10,000 iterations...
3rd May 2019, 11:48 AM
Anna
Anna - avatar
+ 4
If the difference between two consecutive array elements is greater than 1 then that element is missing. You can loop through the array elements and brake your loop when the difference is greater than 1😎
4th May 2019, 3:14 AM
Sanjay Kamath
Sanjay Kamath - avatar
+ 3
Or, iterate through and check if greater neighbor number is +1. If +2 there is missing one. The code for this: https://code.sololearn.com/cyrc24RUSqFm/?ref=app
3rd May 2019, 11:58 AM
Maneren
Maneren - avatar
+ 2
Schindlabua That's probably unbeatable 👌😁
3rd May 2019, 3:37 PM
Anna
Anna - avatar
+ 1
Anna Yeah, kinda missed this fact.
3rd May 2019, 12:56 PM
Maneren
Maneren - avatar
+ 1
You can compare a value of an array and its index plus some offset of the start sequence. For example: https://code.sololearn.com/cwcNIwGpFf3u/?ref=app This works only for sorted arrays. So if one is not sorted sort it.
4th May 2019, 5:12 AM
Dima
0
There's another solution by using arithmetic progression property such @Schindlabua suggested. https://code.sololearn.com/cwfwfu58Fds8/?ref=app
4th May 2019, 7:49 AM
Dima