Check each element in the array with all other elements in the array and keep track of its count and also maintain the max counter which track the element repeats the maximum number of time.
publicvoidMaxRepeatingElement(int[] arrA) {
int maxCounter = 0;
int element = 0;
for (int i = 0; i < arrA.length; i++) {
int counter = 1;
for (int j = i + 1; j < arrA.length; j++) {
if (arrA[i]== arrA[j]) {
counter++;
}
}
if (maxCounter < counter) {
maxCounter = counter;
element = arrA[i];
}
}
System.out.println("Element repeating maximum no of times: "+ element +", maximum count: "+ maxCounter);
}
Sort the array, this will bring all the duplicates together if present. Now navigate the array and keep track of its count and also maintain the max counter which track the element repeats the maximum number of time.
publicvoidmaxRepeatingElementUsingMap(int[] arrA) {
//Will store each character and it's count HashMap<Integer, Integer> map =new HashMap<>();
for (int i = 0; i < arrA.length; i++) {
if (map.containsKey(arrA[i])) {
map.put(arrA[i], map.get(arrA[i]) + 1);
} else {
map.put(arrA[i], 1);
}
}
//traverse the map and track the element which has max count Iterator entries = map.entrySet().iterator();
int maxCount = 0;
int element = arrA[0];
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
int count = (Integer) entry.getValue();
if (maxCount < count) {
maxCount = count;
element = (Integer) entry.getKey();
}
}
System.out.println("Element repeating maximum no of times: "+ element +", maximum count: "+ maxCount);
}
We can have a binary search tree with an extra field count, which indicates the number of times an element appeared in the input.
Node of the Binary Search Tree (used in this approach) will be as follows.
1
2
3
4
5
6
class TreeNode {
int val;
int count;
TreeNode left;
TreeNode right;
}
Insert elements in BST one by one and if an element is already present then increment the count of the node.
Now do the inorder traversal on the tree, keeping track of the count and value of max element in the tree.