Quickest Way to Find Missing Number in an Array of Numbers

Quickest way to find missing number in an array of numbers

You can do this in O(n). Iterate through the array and compute the sum of all numbers. Now, sum of natural numbers from 1 to N, can be expressed as Nx(N+1)/2. In your case N=100.

Subtract the sum of the array from Nx(N+1)/2, where N=100.

That is the missing number. The empty slot can be detected during the iteration in which the sum is computed.

// will be the sum of the numbers in the array.
int sum = 0;
int idx = -1;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == 0)
{
idx = i;
}
else
{
sum += arr[i];
}
}

// the total sum of numbers between 1 and arr.length.
int total = (arr.length + 1) * arr.length / 2;

System.out.println("missing number is: " + (total - sum) + " at index " + idx);

What is the quickest way to find all missing numbers in unsorted array

Obviously the numbers are in a certain range or it does not make sense to talk about missing numbers. Therefore a counting sort can be applied. Then do a linear scan through the array to find the holes. Alternatively you could scan the counts from the sorting step to find the missing elements.

This all runs in O(n).

Example:
The following array is given 6,1,7,8,3,4,9,1,10,3.

Now calculate how often each number appears in the array by going once through the array and incrementing the count for each encountered number:

number 1  2  3  4  5  6  7  8  9 10
count 2 0 2 1 0 1 1 1 1 1

You immediately see that 2 and 5 did appear 0 times and are therefore missing.

The counts can also be used to come up with a sorted array: we need 2 times 1, two times 3, one time 4, and so on.

1  1  3  3  4  6  7  8  9 10

Fastest way to find 2 missing numbers in an array

The simple way (and pretty fast too:)

a = [1,2,3,5,7]
b = (1..7).to_a
p b-a #=> [4, 6]

Quickest way to find missing number in an array of numbers

You can do this in O(n). Iterate through the array and compute the sum of all numbers. Now, sum of natural numbers from 1 to N, can be expressed as Nx(N+1)/2. In your case N=100.

Subtract the sum of the array from Nx(N+1)/2, where N=100.

That is the missing number. The empty slot can be detected during the iteration in which the sum is computed.

// will be the sum of the numbers in the array.
int sum = 0;
int idx = -1;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == 0)
{
idx = i;
}
else
{
sum += arr[i];
}
}

// the total sum of numbers between 1 and arr.length.
int total = (arr.length + 1) * arr.length / 2;

System.out.println("missing number is: " + (total - sum) + " at index " + idx);

JavaScript find missing number in array

You can do this with the use of indexOf function:

var a = [5],  count = 5;var missing = new Array();
for (var i = 1; i <= count; i++) { if (a.indexOf(i) == -1) { missing.push(i); }}console.log(missing); // to check the result.

Find the Missing no from an array the efficient way

Quickly written and tested (in terms of times performances against your code, but not in term of possible edges cases/mistakes, for instance, if array is 0...10, it won't work, but I'll let you work on the edges cases, since I focused mainly on the main cases, cases which might be covered during an edit and the end of the question)

Your current code:

func findMissingNo(arrA: [Int]) -> [Int] {
let firstIndex = arrA.first ?? 0
let lastIndex = arrA.last ?? 0
let rslt = Array(firstIndex...lastIndex)
let missingNoArray = rslt.filter{ !arrA.contains($0)}
return missingNoArray
}
let numberArray = [11,12,14,15,18]
let missing1 = findMissingNo(arrA: numberArray)
print("Missing1: \(missing1)")

My attempt:

func findMissingNo2(arrA: [Int]) -> [Int] {
var missingNumbers: [Int] = []
guard arrA.count > 2 else { return missingNumbers }
for i in 0...arrA.count-2 {
var current = arrA[i]
let next = arrA[i+1]
if next != current + 1 {
current += 1
while current != next {
missingNumbers.append(current)
current += 1
}
}
}
return missingNumbers
}

let missing2 = findMissingNo2(arrA: numberArray)
print("Missing1: \(missing2)")

Creating a big batch:

var array = Array(0...1000)
for _ in 0...10 {
if let index = array.indices.randomElement() {
let value = array.remove(at: index)
print("removed: \(value)") //To check just in case that's the good value returned by the methods
}
}

Testing:

let date1 = Date()
for _ in 0...100 {
let missing = findMissingNo(arrA: array)
print(missing)
}
print(Date().timeIntervalSince(date1)) //18.617565035820007

let date2 = Date()
for _ in 0...100 {
let missing = findMissingNo2(arrA: array)
print(missing)
}
print(Date().timeIntervalSince(date2)) //0.09566605091094971

print("---End")
print("")

For the time, I got: 18.857954025268555 vs 0.09159696102142334, a big factor difference (~200 times).

Why is there such a big difference?

Because of

let missingNoArray = rslt.filter{ !arrA.contains($0)}

It means:

for each number in result, check if arrayA contains that number.

->

for each number in result, for each number in arrayA (with a stop condition, so it's not a full iteration, but "almost" in term of complexity) check if there is a match...

Here there is a "double" (which is in fact not double, but n?) iteration that you missed.

I tested first with bigger value (array from "0 to 100000"), but it was taking too much time, with that "low number of values", the difference can already be seen.

Instead, you could use a Set:

let missingNoArray = Array(Set(rslt).subtracting(Set(arrA))).sorted()

It's faster than you method in my tests, (double my solution (0.21 ~ 0.22) in time performances), but still much faster than yours.
I added the sorted(), which may or may not be important in your solution, but will add time consumption since Set aren't ordered.

For the edges cases (ie: [3], [3, 4], [3, 8])

guard arrA.count > 2 else { return missingNumbers }

==>

guard !arrA.isEmpty else { return [] }
guard arrA.count > 2 else {
if arrA[0] + 1 >= arrA[1] {
return []
} else {
return Array((arrA[0] + 1)...arrA[1]).dropLast() //Because last will be arrA[1] which is present)
}
}

Find out n numbers of missing elements from an array in java

int[] numbers = { 11, 6, 4, 5, 7, 1 };
Arrays.sort(numbers);
int numbersArrayIndex = 0;
for (int i = 0; i < numbers[numbers.length - 1]; i++) {
if (i == numbers[numbersArrayIndex]) {
numbersArrayIndex++;
}
else {
System.out.println(i);
}
}

Quickest way to find missing number in an array of numbers

You can do this in O(n). Iterate through the array and compute the sum of all numbers. Now, sum of natural numbers from 1 to N, can be expressed as Nx(N+1)/2. In your case N=100.

Subtract the sum of the array from Nx(N+1)/2, where N=100.

That is the missing number. The empty slot can be detected during the iteration in which the sum is computed.

// will be the sum of the numbers in the array.
int sum = 0;
int idx = -1;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == 0)
{
idx = i;
}
else
{
sum += arr[i];
}
}

// the total sum of numbers between 1 and arr.length.
int total = (arr.length + 1) * arr.length / 2;

System.out.println("missing number is: " + (total - sum) + " at index " + idx);


Related Topics



Leave a reply



Submit