// C# program to find total count of an element
using System;
using System.Collections;
using System.Collections.Generic;
public class GFG {
static Dictionary<int, List<int> > store;
static int lower_bound(List<int> a, int low, int high,
int key)
{
if (low > high) {
return low;
}
int mid = low + (high - low) / 2;
if (key <= a[mid]) {
return lower_bound(a, low, mid - 1, key);
}
return lower_bound(a, mid + 1, high, key);
}
static int upper_bound(List<int> a, int low, int high,
int key)
{
if (low > high || low == a.Count)
return low;
int mid = low + (high - low) / 2;
if (key >= a[mid]) {
return upper_bound(a, mid + 1, high, key);
}
return upper_bound(a, low, mid - 1, key);
}
// Returns frequency of element in arr[left-1..right-1]
static int findFrequency(int[] arr, int n, int left,
int right, int element)
{
// Find the position of first occurrence of element
int a = lower_bound(store[element], 0,
store[element].Count, left);
// Find the position of last occurrence of element
int b = upper_bound(store[element], 0,
store[element].Count, right);
return b - a;
}
// Driver code
public static void Main(string[] args)
{
int[] arr = { 2, 8, 6, 9, 8, 6, 8, 2, 11 };
int n = arr.Length;
// Storing the indexes of an element in the map
store = new Dictionary<int, List<int> >();
for (int i = 0; i < n; ++i) {
if (!store.ContainsKey(arr[i]))
store.Add(arr[i], new List<int>());
store[arr[i]].Add(i
+ 1); // starting index from 1
}
// Print frequency of 2 from position 1 to 6
Console.WriteLine("Frequency of 2 from 1 to 6 = "
+ findFrequency(arr, n, 1, 6, 2));
// Print frequency of 8 from position 4 to 9
Console.WriteLine("Frequency of 8 from 4 to 9 = "
+ findFrequency(arr, n, 4, 9, 8));
}
}
// This code is contributed by Karandeep1234