PowerShell for Windows Admins

Oct 31 2018   4:23AM GMT

Find a missing integer–alternative solution

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


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 {
param (


#$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


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


 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: