Oct 31 2018   4:23AM GMT

# Find a missing integer–alternative solution

Profile: Richard Siddaway

Tags:
Powershell

In my recent post about finding a missing integer in an array of numbers I didn’t spell out the assumptions. In this post I’ll explain those assumptions and show you how to Find a missing integer–alternative solution.

The assumptions were:

The sequence of numbers in the array starts at 1

The values increment by 1

If the sequence doesn’t start at 1 the technique fails as the expected sum being n(n+1)/2 breaks down.

As an alternative you can calculate the expected sum by finding the average of the numbers in the sequence and multiplying by the number of expected entries in the sequence.

function get-missinginteger {
[CmdletBinding()]
param (
[int[]]\$iarray,

[int]\$expectedlength
)

#\$expectedSum = (\$expectedlength * (\$expectedlength + 1) ) / 2

# don’t know if array is in numeric order
\$sarray = \$iarray | sort

\$expectedSum = \$expectedlength * ((\$sarray[0] + \$sarray[-1]) / 2)

\$actualsum = 0
foreach (\$n in \$iarray) {
\$actualsum += \$n
}

\$missingnumber = \$expectedSum – \$actualsum
\$missingnumber
}

I’ve changed the function name. The only other change is to sort the array and calculate the expected sum using the average

\$sarray = \$iarray | sort
\$expectedSum = \$expectedlength * ((\$sarray[0] + \$sarray[-1]) / 2)

The examples from the previous post work as does

PS> \$iarray = 6,7,8,9,10,11,12,13,14,15,16,17,18,20,21,22,23,24,25

get-missinginteger -iarray \$iarray -expectedlength 20

19