Search code examples
javaarraysalgorithmdictionarytreemap

Finding the sum of the most commonly occurring number in an array with best optimized time complexity


If I have an array {2,3,4,5,6,5,7}, the output of this should be 10, as 5 is the most commonly occurring integer occurring twice. Importantly, I want to make this program optimized to its best time complexity while stating how I calculated it and also the space complexity, all in Java.

I am trying to use Treemap, but don't know is it the best solution or how to write the best optimized code in Java, along with other calculations. Please help.


Solution

  • The best solution is with a bucket array, you run on your array once O(n), and count the number of appearances of each number. at the and you find the maximum bucket and print - bucket_value*bucket_number.