1

An array is given :array(1,2,3,4,6,8,9). Here 2 numbers are missing. My question is how to find , if more than 1 numbers are missing.

asked Nov 25, 2016 at 13:38
1
  • 5
    Some example code and a programming language would be useful, you're essentially just asking us to write your code Commented Nov 25, 2016 at 13:40

3 Answers 3

3

If the array is not sorted, sort it, then look for an increase of more than 1 in neighbor elements.

answered Nov 25, 2016 at 13:41
1

You could extract min and max, and compare array to the range from min and max.

Ruby example :

array = [1,2,3,4,6,8,9]
min, max = array.minmax
missing = (min..max).to_a - array
#=> [5,7]

or sort and look for gaps that are bigger than 1

array = [1,2,3,4,6,8,9,12]
array.sort.each_cons(2) do |a,b|
 if (b-1) > a then
 (a+1..b-1).each do |i|
 puts "#{i} is missing"
 end
 end
end
# 5 is missing
# 7 is missing
# 10 is missing
# 11 is missing
answered Nov 25, 2016 at 13:45
2
  • I really like the id of getting max and min. You can just substract them and check against the array length to find out, how many are missing. Commented Nov 25, 2016 at 14:26
  • You need to check that the array doesn't have duplicates, and only contains integers. Otherwise 3,3,5 and 3,3.1,5 will match Commented Nov 25, 2016 at 14:56
0

In Javascript (the principles should carry over), you can sort it numerically then work your way through the array looking for numbers that aren't there. When you find them you can make a note of it a and move on.

Have a look here:

var numberArray = [1, 2, 3, 4, 6, 8, 9, 15, 12];
var missingArray = [];
function findMissing() {
 var sortedArray = numberArray.sort(function(a, b) {
 return a - b
 });
 var currentNo = sortedArray[0];
 for (let i = 0; i < sortedArray.length; i++) {
 if (sortedArray[i] == currentNo) {
 currentNo++
 } else {
 missingArray.push(currentNo);
 i--;
 currentNo++;
 }
 }
 document.querySelector(".problem").innerHTML = "Array numbers are " + numberArray;
 document.querySelector(".result").innerHTML = "Missing numbers are " + missingArray;
}
findMissing();
<div class="problem"></div>
<div class="result"></div>

Hope this helps.

answered Nov 25, 2016 at 14:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.