Sort the array, then, all repeating elements are next to each other.
Simply iterate the array, while holding a maxSeen
and currSeen
counters, if current element equals last element, increase currSeen
, otherwise - reset currSeen
, and replace maxSeen
if the currSeen
is bigger than it.
Sorting is O(nlogn), and iterating once is O(n), so total of O(nlogn + n) = O(nlogn)
It's homework, so following this guidelines to create a code should be your task. Good Luck!
As a side note, since this is at least as hard as Element Distinctness Problem, and it cannot be done better than O(nlogn) using comparisons based algorithms.
Side note two, it can be done in O(n)
time + space using hash-tables.
Create a histogram of the data, which is a hash-map, inwhich a key is an element, and the value is number of occurances. Then, the problem decays to finding maximal value in this hash table.
Building the table is O(n)
average case, and finding maximum is O(n)
.
This however uses O(n)
extra memory, and might deteriorate to O(n^2)
time under worst case behavior.