I stumbled across a set of programmer interview questions recently. They raised some interesting problems that I thought would be fun to show a PowerShell answer. This is the first of them – find a missing integer in an array.

Consider an array of integers. It should have 10 members:

$iarray = 1,2,3,4,5,6,7,8,9,10

But what if one is missing

$iarray = 1,2,3,4,5,6,8,9,10

In this case the number 7 is missing.

This problem assumes that there is a regular increment between members of the array – in this case 1. In mathematical terms its a series.

function get-missingnumber {

[CmdletBinding()]

param (

[int[]]$iarray,

[int]$expectedlength

)

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

$actualsum = 0

foreach ($n in $iarray) {

$actualsum += $n

}

$missingnumber = $expectedSum – $actualsum

$missingnumber

}

The solution is to find the expected sum of the series which is found using

(n * (n + 1)) / 2

where n is the expected length of the series. 1 is the increment between members of the series. You can generalise this for any increment but that’s left as an exercise for you.

Then calculate the actual sum by looping through the array and summing the values.

The missing number is the difference between the expected sum and the actual sum

Here’s some examples

PS> ## 10 integers – number 7 missing

PS> $iarray = 1,2,3,4,5,6,8,9,10

PS> get-missingnumber -iarray $iarray -expectedlength 10

7

PS> ## 25 integers – number 19 missing

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

PS> get-missingnumber -iarray $iarray -expectedlength 25

19

A quick way to generate the array to play with:

PS> $r = Get-Random -Maximum 26 -Minimum 1

PS> $iarray = 1..25 | where {$psitem -ne $r}

PS> get-missingnumber -iarray $iarray -expectedlength 25

22

PS> $r

22