Php Program for Range Queries for Frequencies of array elements
Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type.Â
Examples:Â
Â
Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};
left = 2, right = 8, element = 8
left = 2, right = 5, element = 6
Output : 3
1
The element 8 appears 3 times in arr[left-1..right-1]
The element 6 appears 1 time in arr[left-1..right-1]
Naive approach: is to traverse from left to right and update count variable whenever we find the element.Â
Below is the code of Naive approach:-Â
Â
PHP
<?php
function findFrequency(& $arr , $n , $left ,
$right , $element )
{
$count = 0;
for ( $i = $left - 1; $i <= $right ; ++ $i )
if ( $arr [ $i ] == $element )
++ $count ;
return $count ;
}
$arr = array (2, 8, 6, 9, 8, 6, 8, 2, 11);
$n = sizeof( $arr );
echo "Frequency of 2 from 1 to 6 = " .
findFrequency( $arr , $n , 1, 6, 2) ."
";
echo "Frequency of 8 from 4 to 9 = " .
findFrequency( $arr , $n , 4, 9, 8);
?>
|
Output:Â
Frequency of 2 from 1 to 6 = 1
Frequency of 8 from 4 to 9 = 2
Time complexity of this approach is O(right – left + 1) or O(n)Â
Auxiliary space: O(1)
Please refer complete article on Range Queries for Frequencies of array elements for more details!
Last Updated :
06 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...