PHP Program to Find Missing Number in Array
n*(n+1)/2 and subtracting the actual sum of array elements using array_sum() in PHP.Examples
How to Think About It
n*(n+1)/2. Then find the sum of the given array. The difference between these two sums is the missing number.Algorithm
Code
<?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]);
Dry Run
Let's trace the example array [1, 2, 4, 5, 6] through the code
Calculate n
Array length is 5, so n = 5 + 1 = 6
Calculate expected sum
expectedSum = 6 * (6 + 1) / 2 = 6 * 7 / 2 = 21
Calculate actual sum
actualSum = 1 + 2 + 4 + 5 + 6 = 18
Find missing number
missing = expectedSum - actualSum = 21 - 18 = 3
Output result
Print 3 as the missing number
| Step | Value |
|---|---|
| n | 6 |
| expectedSum | 21 |
| actualSum | 18 |
| missing | 3 |
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
<?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]);
<?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]);
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sum formula | O(n) | O(1) | Fastest and simplest for large arrays |
| Loop with presence array | O(n) | O(n) | Easy to understand, uses extra memory |
| Sorting and checking | O(n log n) | O(1) | Works when array order matters or no extra space allowed |
n*(n+1)/2 to quickly find the missing number without extra loops.