0
0
PhpProgramBeginner · 2 min read

PHP Program to Find Missing Number in Array

You can find the missing number in an array by calculating the expected sum with n*(n+1)/2 and subtracting the actual sum of array elements using array_sum() in PHP.
📋

Examples

Input[1, 2, 4, 5, 6]
Output3
Input[2, 3, 1, 5]
Output4
Input[1, 2, 3, 4, 5]
OutputNo missing number
🧠

How to Think About It

To find the missing number, first understand that the array should contain numbers from 1 to n with one missing. Calculate the total sum of numbers from 1 to n using the formula n*(n+1)/2. Then find the sum of the given array. The difference between these two sums is the missing number.
📐

Algorithm

1
Get the input array
2
Calculate n as the length of the array plus one
3
Calculate the expected sum using n*(n+1)/2
4
Calculate the actual sum of the array elements
5
Subtract actual sum from expected sum to find the missing number
6
If the difference is zero, print 'No missing number', else print the missing number
💻

Code

php
<?php
function findMissingNumber(array $arr) {
    $n = count($arr) + 1;
    $expectedSum = $n * ($n + 1) / 2;
    $actualSum = array_sum($arr);
    $missing = $expectedSum - $actualSum;
    if ($missing == 0) {
        echo "No missing number";
    } else {
        echo $missing;
    }
}

// Example usage
findMissingNumber([1, 2, 4, 5, 6]);
Output
3
🔍

Dry Run

Let's trace the example array [1, 2, 4, 5, 6] through the code

1

Calculate n

Array length is 5, so n = 5 + 1 = 6

2

Calculate expected sum

expectedSum = 6 * (6 + 1) / 2 = 6 * 7 / 2 = 21

3

Calculate actual sum

actualSum = 1 + 2 + 4 + 5 + 6 = 18

4

Find missing number

missing = expectedSum - actualSum = 21 - 18 = 3

5

Output result

Print 3 as the missing number

StepValue
n6
expectedSum21
actualSum18
missing3
💡

Why This Works

Step 1: Calculate expected sum

The formula n*(n+1)/2 gives the sum of all numbers from 1 to n, which is what the array should contain if no number was missing.

Step 2: Calculate actual sum

Sum all elements in the given array using array_sum() to find what numbers are actually present.

Step 3: Find missing number

Subtracting the actual sum from the expected sum gives the missing number because that difference is exactly the number not in the array.

🔄

Alternative Approaches

Using a loop to find missing number
php
<?php
function findMissingNumberLoop(array $arr) {
    $n = count($arr) + 1;
    $present = array_fill(1, $n - 1, false);
    foreach ($arr as $num) {
        $present[$num] = true;
    }
    for ($i = 1; $i <= $n; $i++) {
        if (!isset($present[$i]) || !$present[$i]) {
            echo $i;
            return;
        }
    }
    echo "No missing number";
}

findMissingNumberLoop([1, 2, 4, 5, 6]);
This method uses extra memory to track presence but is easy to understand and works well for small arrays.
Sorting and checking consecutive numbers
php
<?php
function findMissingNumberSort(array $arr) {
    sort($arr);
    $n = count($arr) + 1;
    for ($i = 0; $i < count($arr); $i++) {
        if ($arr[$i] != $i + 1) {
            echo $i + 1;
            return;
        }
    }
    echo "No missing number";
}

findMissingNumberSort([1, 2, 4, 5, 6]);
Sorting changes the array order and takes more time but helps find the missing number by checking sequence.

Complexity: O(n) time, O(1) space

Time Complexity

Calculating the sum of array elements takes O(n) time, where n is the number of elements. The rest are constant time operations.

Space Complexity

Only a few variables are used for sums and counts, so space complexity is O(1), constant space.

Which Approach is Fastest?

The sum formula method is fastest and uses least memory compared to looping with extra arrays or sorting.

ApproachTimeSpaceBest For
Sum formulaO(n)O(1)Fastest and simplest for large arrays
Loop with presence arrayO(n)O(n)Easy to understand, uses extra memory
Sorting and checkingO(n log n)O(1)Works when array order matters or no extra space allowed
💡
Use the sum formula n*(n+1)/2 to quickly find the missing number without extra loops.
⚠️
Forgetting to add 1 to the array length to get the correct total count including the missing number.