We have to find element(s) in array that are missing from an array in range from array minimum to array maximum.
Examples:
Input : arr[] = (1, 2, 3, 4, 6, 7, 8)
Output : 5
The array minimum is 1 and maximum is
8. The missing element in range from
1 to 8 is 5.
Input : arr[] = (10, 11, 14, 15)
Output : 12, 13
This problem can be solved by iterating in an array by observing the contiguous difference between elements. But in PHP we can make use of some inbuilt functions to solve the problem.
We will have to use the below two functions for this purpose:
- range() function: This function is used to create an array of elements of any kind such as integer, alphabets within a given range(from low to high) i.e, list’s first element is considered as low and last one is considered as high.
- array_diff() function: if we have an array of elements, we can find missing element(s) by comparing two arrays.
The idea to solve this problem using two inbuilt functions is to, first use range() function to create a new array from starting element and maximum element of original array using max() function. After this we apply array_diff() function to compare newly created array and original array thus getting all the missing elements of the original array.
<?php
function not_present($list)
{
$new_array = range(min($list), max($list));
return array_diff($new_array, $list);
}
print_r(not_present(array(1, 2, 3, 4, 7, 8)));
print_r(not_present(array(10, 11, 12, 14, 15, 16)));
?>
|
Output:
Array
(
[4] => 5
[5] => 6
)
Array
(
[3] => 13
)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
11 Mar, 2018
Like Article
Save Article