Find Missing number in an array

<?php

	// find missing element in the given array
	$array = array(1,2,3,5);

	// calculate length of given array
	$length = count($array);

	// actual length of given array
	$actual_length = $length + 1;

	// Calculate the sum of first n natural numbers as total sum = n*(n+1)/2
	$total_sum = ( $actual_length * ( $actual_length + 1 ) ) / 2;

	// missing number
	$missing_number = $total_sum - array_sum($array);

	echo $missing_number;

?>

OUTPUT : 4

Leave a Comment