VOOZH about

URL: https://www.geeksforgeeks.org/php/php-second-frequent-element-array/

⇱ PHP Second most frequent element in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

PHP Second most frequent element in an array

Last Updated : 20 Aug, 2024

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

Using array_count_values and array_keys

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".


Output
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".


Output
Second most frequent string is: for

Using forEach method

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:


Output
Second most frequent element: 4

Using Min-Heap

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:

  1. Count the frequency of each element in the array.
  2. Use a Min-Heap to keep track of the two most frequent elements.
  3. The root of the heap will be the second most frequent element.

Example: Here's the implementation of above approach.


Output
Second most frequent element is: 9
Comment
Article Tags: