Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP program to find the numbers within a given array that are missing
To find missing numbers from a range of positive integers, we can compare an existing array with an expected sequence. Here's a PHP program that finds the first few missing positive numbers from a given array.
Example
<?php
function missing_nums($my_arr, $arr_len, $val)
{
sort($my_arr);
$i = 0;
// Skip negative numbers and zeros
while ($i < $arr_len && $my_arr[$i] <= 0)
$i++;
$count = 0;
$current_num = 1;
// Find missing numbers by comparing with expected sequence
while ($count < $val && $i < $arr_len)
{
if ($my_arr[$i] != $current_num)
{
echo $current_num . " ";
$count++;
}
else
$i++;
$current_num++;
}
// Print remaining missing numbers if needed
while ($count < $val)
{
echo $current_num . " ";
$current_num++;
$count++;
}
}
$my_arr = array(6, 7, 9);
$arr_len = sizeof($my_arr);
$val = 5;
echo "The missing numbers in the array are: ";
missing_nums($my_arr, $arr_len, $val);
?>
Output
The missing numbers in the array are: 1 2 3 4 5
How It Works
The missing_nums function first sorts the input array to process numbers in ascending order. It skips any negative numbers or zeros since we're looking for missing positive integers. The function then compares each expected number (starting from 1) with the actual array elements. When a mismatch is found, that number is considered missing and gets printed.
The algorithm continues until it finds the specified number of missing values. If the array runs out of elements before finding enough missing numbers, it continues printing the next expected positive integers.
Conclusion
This approach efficiently finds missing positive numbers by sorting the array first and then comparing expected values with actual array elements. The function allows you to specify how many missing numbers you want to find.
