Find the element with highest occurrences in an array [java]

I have to find the element with highest occurrences in a double array.
I did it like this:

int max = 0;
for (int i = 0; i < array.length; i++) {
       int count = 0;
       for (int j = 0; j < array.length; j++) {
         if (array[i]==array[j])
             count++;
   }
  if (count >= max)
      max = count;
 }

The program works, but it is too slow! I have to find a better solution, can anyone help me?

Update:

  • As Maxim pointed out, using HashMap would be a more appropriate choice than Hashtable here.
  • The assumption here is that you are not concerned with concurrency. If synchronized access is needed, use ConcurrentHashMap instead.

You can use a HashMap to count the occurrences of each unique element in your double array, and that would:

  • Run in linear O(n) time, and
  • Require O(n) space

Psuedo code would be something like this:

  • Iterate through all of the elements of your array once: O(n)
    • For each element visited, check to see if its key already exists in the HashMap: O(1), amortized
    • If it does not (first time seeing this element), then add it to your HashMap as [key: this element, value: 1]. O(1)
    • If it does exist, then increment the value corresponding to the key by 1. O(1), amortized
  • Having finished building your HashMap, iterate through the map and find the key with the highest associated value – and that’s the element with the highest occurrence. O(n)

A partial code solution to give you an idea how to use HashMap:

import java.util.HashMap;
...

    HashMap hm = new HashMap();
    for (int i = 0; i < array.length; i++) {
        Double key = new Double(array[i]);
        if ( hm.containsKey(key) ) {
            value = hm.get(key);
            hm.put(key, value + 1);
        } else {
            hm.put(key, 1);
        }
    }

I’ll leave as an exercise for how to iterate through the HashMap afterwards to find the key with the highest value; but if you get stuck, just add another comment and I’ll get you more hints =)

6

Use Collections.frequency option:

 List<String> list = Arrays.asList("1", "1","1","1","1","1","5","5","12","12","12","12","12","12","12","12","12","12","8");
      int max = 0;
      int curr = 0;
      String currKey =  null;
      Set<String> unique = new HashSet<String>(list);

          for (String key : unique) {
                curr = Collections.frequency(list, key);

               if(max < curr){
                 max = curr;
                 currKey = key;
                }
            }

          System.out.println("The number "  + currKey + " happens " + max + " times");

Output:

The number 12 happens 10 times

2

The solution with Java 8

       int result = Arrays.stream(array)
           .boxed()
           .collect(Collectors.groupingBy(i->i,Collectors.counting()))
           .values()
           .stream()
           .max(Comparator.comparingLong(i->i))
           .orElseThrow(RuntimeException::new));

0

I will suggest another method. I don’t know if this would work faster or not.

Quick sort the array. Use the built in Arrays.sort() method.

Now compare the adjacent elements.
Consider this example:

1 1 1 1 4 4 4 4 4 4 4 4 4 4 4 4 9 9 9 10 10 10 29 29 29 29 29 29

When the adjacent elements are not equal, you can stop counting that element.

2

Solution 1: Using HashMap

class test1 {
    public static void main(String[] args) {

    int[] a = {1,1,2,1,5,6,6,6,8,5,9,7,1};
    // max occurences of an array
    Map<Integer,Integer> map = new HashMap<>();
      int max = 0 ; int chh = 0 ;
      for(int i = 0 ; i < a.length;i++) {
          int ch = a[i];
          map.put(ch, map.getOrDefault(ch, 0) +1);
      }//for
      Set<Entry<Integer,Integer>> entrySet =map.entrySet();

      for(Entry<Integer,Integer> entry : entrySet) {
          if(entry.getValue() > max) {max = entry.getValue();chh = entry.getKey();}

      }//for
    System.out.println("max element => " + chh);
    System.out.println("frequency => " + max);
    }//amin
}
/*output =>
max element => 1
frequency => 4

*/

Solution 2 : Using count array

public class test2 {
    public static void main(String[] args) {
         int[] a = {1,1,2,1,5,6,6,6,6,6,8,5,9,7,1};
    int max = 0 ; int chh = 0;
    int count[] = new int[a.length];
    for(int i = 0 ; i <a.length ; i++) {
        int ch = a[i];
        count[ch] +=1 ;
    }//for

    for(int i = 0 ; i <a.length ;i++)  {
        int ch = a[i];
        if(count[ch] > max) {max = count[ch] ; chh = ch ;}
    }//for
         System.out.println(chh); 
    }//main
}

Here’s a java solution —

        List<Integer> list = Arrays.asList(1, 2, 2, 3, 2, 1, 3);
        Set<Integer> set = new HashSet(list);
        int max = 0;
        int maxtemp;
        int currentNum = 0;
        for (Integer k : set) {
            maxtemp = Math.max(Collections.frequency(list, k), max);
            currentNum = maxtemp != max ? k : currentNum;
            max = maxtemp;
        }
        System.out.println("Number :: " + currentNum + " Occurs :: " + max + " times");

int[] array = new int[] { 1, 2, 4, 1, 3, 4, 2, 2, 1, 5, 2, 3, 5 };

Long max = Arrays.stream(array).boxed().collect(Collectors.groupingBy(i -> i, Collectors.counting())).values()
                .stream().max(Comparator.comparing(Function.identity())).orElse(0L);
    

1

public static void main(String[] args) {

   int n;

   int[] arr;

    Scanner in = new Scanner(System.in);
    System.out.println("Enter Length of Array");
    n = in.nextInt();
    arr = new int[n];
    System.out.println("Enter Elements in array"); 

    for (int i = 0; i < n; i++) {
        arr[i] = in.nextInt();
    }

    int greatest = arr[0];

    for (int i = 0; i < arr.length; i++) {
        if (arr[i] > greatest) {
            greatest = arr[i];
        }

    } 

    System.out.println("Greatest Number " + greatest);

    int count = 0;

    for (int i = 0; i < arr.length; i++) {
        if (greatest == arr[i]) {
            count++;
        }
    }

    System.out.println("Number of Occurance of " + greatest + ":" + count + " times");

    in.close();
}

In continuation to the pseudo-code what you’ve written try the below written code:-

public static void fetchFrequency(int[] arry) {
        Map<Integer, Integer> newMap = new TreeMap<Integer, Integer>(Collections.reverseOrder());
        int num = 0;
        int count = 0;
        for (int i = 0; i < arry.length; i++) {
            if (newMap.containsKey(arry[i])) {
                count = newMap.get(arry[i]);
                newMap.put(arry[i], ++count);
            } else {
                newMap.put(arry[i], 1);
            }
        }
        Set<Entry<Integer, Integer>> set = newMap.entrySet();
        List<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
        Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {

            @Override
            public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
                return (o2.getValue()).compareTo(o1.getValue());
            }
        });

        for (Map.Entry<Integer, Integer> entry : list) {
            System.out.println(entry.getKey() + " ==== " + entry.getValue());
            break;
        }
        //return num;
    }

This is how i have implemented in java..

import java.io.*;
class Prog8
{
    public static void main(String[] args) throws IOException 
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Input Array Size:");
        int size=Integer.parseInt(br.readLine());
        int[] arr= new int[size];
        System.out.println("Input Elements in Array:");
        for(int i=0;i<size;i++)
            arr[i]=Integer.parseInt(br.readLine());
        int max = 0,pos=0,count = 0;
        for (int i = 0; i < arr.length; i++)
        {
            count=0;
            for (int j = 0; j < arr.length; j++) 
            {
                if (arr[i]==arr[j])
                    count++;
            }
            if (count >=max)
            {
                max = count;
                pos=i;
            }
        }

        if(max==1)
            System.out.println("No Duplicate Element.");
        else
            System.out.println("Element:"+arr[pos]+" Occourance:"+max);
    }
}

Find the element with the highest occurrences in an array using java 8 is given below:

final Long maxOccurrencesElement = arr.stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                .entrySet()
                .stream()
                .max((o1, o2) -> o1.getValue().compareTo(o2.getValue()))
                .get()
                .getKey();

You can solve this problem in one loop with without using HashMap or any other data structure in O(1) space complexity.

Initialize two variables count = 0 and max = 0 (or Integer.MIN_VALUE if you have negative numbers in your array)

The idea is you will scan through the array and check the current number,

  • if it is less than your current max…then do nothing
  • if it is equal to your max …then increment the count variable
  • if it is greater than your max..then update max to current number and set count to 1

Code:

int max = 0, count = 0;
for (int i = 0; i < array.length; i++) {
    int num = array[i];
    if (num == max) {
        count++;
    } else if (num > max) {
        max = num;
        count = 1;
    }
}

1

Here is Ruby SOlution:

def maxOccurence(arr)
  m_hash = arr.group_by(&:itself).transform_values(&:count)
  elem = 0, elem_count = 0
  m_hash.each do |k, v|
    if v > elem_count
        elem = k
        elem_count = v
    end
  end
  "#{elem} occured #{elem_count} times"
end

p maxOccurence(["1", "1","1","1","1","1","5","5","12","12","12","12","12","12","12","12","12","12","8"])

output:

"12 occured 10 times"

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật