![]() |
VOOZH | about |
Given an array we have to find the second most frequent element present in it. Examples:
Input : array(3, 3, 4, 5, 5, 5, 9, 8, 8, 8, 8, 8);
Output : Second most frequent element is: 5
Input : array("geeks", "for", "geeks");
Output : Second most frequent element is: for
Here are some common approaches
At first, we make a new array containing the frequency of all the elements with values as key and count as values using the array_count_values.
Sorting the new array in reverse order using arsort, then take all the keys of the sorted array using array_keys. Second key will be the second most frequent element of the original array.
Example : In this example we counts the frequency of elements in an array, sorts them in descending order, and prints the second most frequent element. The second most frequent element is "2".
Second most frequent element is: 4
Example 2: In this example we counts the frequency of elements in an array, sorts them in descending order, and then prints the second most frequent element. The second most frequent string is "for".
Second most frequent string is: for
This manual method in PHP iterates through an array to count occurrences of each element, updating variables to track the second most frequent element without relying on built-in functions like array_count_values or arsort.
Example:
Second most frequent element: 4
A Min-Heap can be used to keep track of the two most frequent elements in the array. The idea is to iterate through the array to count the frequency of each element. Then, we maintain a Min-Heap of size 2, where the root of the heap always contains the second most frequent element.
Steps:
Example: Here's the implementation of above approach.
Second most frequent element is: 9