Skip to content

Instantly share code, notes, and snippets.

@anil477
Created June 20, 2017 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/01799a6e404a2b2cb1156d8de59ea8e3 to your computer and use it in GitHub Desktop.
Save anil477/01799a6e404a2b2cb1156d8de59ea8e3 to your computer and use it in GitHub Desktop.
Count frequency of element in less than O(n)
// http://www.geeksforgeeks.org/find-frequency-of-each-element-in-a-limited-range-array-in-less-than-on-time/
// Given an sorted array of positive integers, count number of occurrences for each element in the array. Assume all elements in the array are less than some constant M.
// Do this without traversing the complete array. i.e. expected time complexity is less than O(n).
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
class Frequency {
public static void binary(int[] a, int l, int h, Map<Integer,Integer> map)
{
// System.out.println(" Method STart low " + l + " high " + h);
if(l>h) {
return;
}
if(a[l] == a[h])
{
//System.out.println(" low " + l + " high " + h);
int value = h - l + 1;
put(map,a[l],h-l+1);
}
else
{
int mid = (l + h)/2;
//System.out.println(" low = " + l + " high " + h + " mid " + mid);
binary(a, l, mid ,map);
binary(a, mid+1, h ,map);
}
}
private static void put(Map<Integer, Integer> map, int key, int value) {
if(map.containsKey(key)){
map.put(key,map.get(key)+value);
} else{
map.put(key, value);
}
}
private static void print(Map<Integer, Integer> map) {
for(Entry<Integer,Integer> entry : map.entrySet()){
System.out.println(entry.getKey() + " Occured " + entry.getValue());
}
}
public static void main(String[] args) {
int[] arr={1, 1, 1, 2, 3, 3, 5, 5,8, 8, 8, 9, 9, 10 };
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
binary(arr, 0, arr.length-1, map);
print(map);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment