![]() |
VOOZH | about |
Given an array arr[] of N integers, the task is to find the most frequent pair of elements in the array. A pair consists of two adjacent elements in the array. If there are multiple pairs with the same maximum frequency, return any one of them.
Examples:
Input: arr[]: {1, 2, 2, 3, 2, 3, 4, 4, 4, 4}
Output: Most Frequent Pair: {4, 4}
Explanation: In the given array, the most frequent pair of elements is {4, 4}. This pair appears three times, which is the maximum frequency among all pairs.Input: arr[]: {1, 2, 3, 4, 5}
Output: Most Frequent Pair: {1, 2}
Explanation: In this array, there are no repeated pairs. Therefore, any adjacent pair can be considered the most frequent. In this example, we chose {1, 2} as the result.Input: {10, 20, 30, 10, 10, 20}
Output: Most Frequent Pair: {10, 20}
Explanation: The array contains the following adjacent pairs:
{10, 20} appears twice.
{20, 30} appears once.
{30, 10} appears once.
{10, 10} appears once.
Among these pairs, {10, 20} is the most frequent with a frequency of 2.
Naïve approach: The basic way to solve the problem is as follows:
The Brute Force approach involves examining all possible pairs of adjacent elements in the array and counting their frequencies. We can iterate through the array, consider each element along with its adjacent element, and maintain a count for each pair. After iterating through the entire array, we find the pair with the maximum frequency.
Below is the code that implements the above approach:
Most Frequent Pair: {4, 4}Time Complexity: O(n2)
Auxiliary Space: O(1)
Efficient Approach: Follow the below idea to solve the problem:
The optimal approach leverages the fact that we only need to find adjacent pairs with the highest frequency. We can do this by iterating through the array once and keeping track of the frequency of each adjacent pair as we go. This approach is more efficient than the brute force method because it requires only a single pass through the array.
Below is the C++ code that implements the above approach:
Most Frequent Pair: {4, 4}Time Complexity: O(n), where n is the number of elements in the input array.
Auxiliary Space: O(k), where k is the number of distinct adjacent pairs in the input array. In practice, k will be much smaller than n, so the space complexity can be considered nearly constant.