Open In App

Find the most Frequent adjacent Element pairs

Last Updated : 06 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++




// C++ code for the above approach:
#include <iostream>
#include <vector>
 
using namespace std;
 
vector<int> findMostFrequentPair(vector<int>& nums)
{
    int maxFrequency = 0;
    vector<int> mostFrequentPair;
 
    // Initialize the frequency to 1
    // for the current pair
    for (int i = 0; i < nums.size() - 1; i++) {
        int currentPairFrequency = 1;
        for (int j = i + 1; j < nums.size(); j++) {
 
            // Increment the
            // frequency if the
            // pair matches.
            if (nums[i] == nums[j]
                && nums[i + 1] == nums[j + 1]) {
                currentPairFrequency++;
            }
        }
 
        if (currentPairFrequency > maxFrequency) {
            maxFrequency = currentPairFrequency;
            mostFrequentPair = { nums[i], nums[i + 1] };
        }
    }
 
    return mostFrequentPair;
}
 
// Drivers code
int main()
{
    vector<int> arr = { 1, 2, 2, 3, 2, 3, 4, 4, 4, 4 };
    vector<int> result = findMostFrequentPair(arr);
 
    // Function Call
    cout << "Most Frequent Pair: {" << result[0] << ", "
        << result[1] << "}" << endl;
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class Main {
    public static List<Integer> findMostFrequentPair(List<Integer> nums) {
        // Create a map to store the frequency of each pair
        Map<List<Integer>, Integer> pairFrequency = new HashMap<>();
        int maxFrequency = 0;
        List<Integer> mostFrequentPair = new ArrayList<>();
 
        for (int i = 0; i < nums.size() - 1; i++) {
            // Create the current pair
            List<Integer> currentPair = List.of(nums.get(i), nums.get(i + 1));
 
            // Update the frequency of the current pair in the map
            pairFrequency.put(currentPair, pairFrequency.getOrDefault(currentPair, 0) + 1);
 
            if (pairFrequency.get(currentPair) > maxFrequency) {
                // If the current pair has a higher frequency, update the most frequent pair
                maxFrequency = pairFrequency.get(currentPair);
                mostFrequentPair = currentPair;
            }
        }
 
        return mostFrequentPair;
    }
 
    public static void main(String[] args) {
        List<Integer> arr = List.of(1, 2, 2, 3, 2, 3, 4, 4, 4, 4);
        List<Integer> result = findMostFrequentPair(arr);
 
        // Function Call
        System.out.println("Most Frequent Pair: {" + result.get(0) + ", " + result.get(1) + "}");
    }
}


Python3




# Python code for the above approach
def findMostFrequentPair(nums):
    maxFrequency = 0
    mostFrequentPair = []
 
    # Initialize the frequency to 1
    # for the current pair
    for i in range(len(nums) - 1):
        currentPairFrequency = 1
        for j in range(i + 1, len(nums)):
 
            # Increment the
            # frequency if the
            # pair matches.
            if nums[i] == nums[j] and i + 1 < len(nums) and j + 1 < len(nums) and nums[i + 1] == nums[j + 1]:
                currentPairFrequency += 1
 
        if currentPairFrequency > maxFrequency:
            maxFrequency = currentPairFrequency
            mostFrequentPair = [nums[i], nums[i + 1]]
 
    return mostFrequentPair
 
 
# Drivers code
arr = [1, 2, 2, 3, 2, 3, 4, 4, 4, 4]
result = findMostFrequentPair(arr)
 
# Function Call
print("Most Frequent Pair: {", result[0], ", ", result[1], "}")
 
# This code is contributed by Sakshi


C#




using System;
using System.Collections.Generic;
 
class MainClass
{
    static List<int> FindMostFrequentPair(List<int> nums)
    {
        int maxFrequency = 0;
        List<int> mostFrequentPair = new List<int>();
 
        // Initialize the frequency to 1
        // for the current pair
        for (int i = 0; i < nums.Count - 1; i++)
        {
            int currentPairFrequency = 1;
            for (int j = i + 1; j < nums.Count; j++)
            {
                // Increment the
                // frequency if the
                // pair matches.
                if (nums[i] == nums[j] && i + 1 < nums.Count && j + 1 < nums.Count && nums[i + 1] == nums[j + 1])
                {
                    currentPairFrequency += 1;
                }
            }
 
            if (currentPairFrequency > maxFrequency)
            {
                maxFrequency = currentPairFrequency;
                mostFrequentPair = new List<int> { nums[i], nums[i + 1] };
            }
        }
 
        return mostFrequentPair;
    }
 
    // Drivers code
    public static void Main(string[] args)
    {
        List<int> arr = new List<int> { 1, 2, 2, 3, 2, 3, 4, 4, 4, 4 };
        List<int> result = FindMostFrequentPair(arr);
 
        // Function Call
        Console.WriteLine($"Most Frequent Pair: {{{result[0]}, {result[1]}}}");
    }
}


Javascript




// JavaScript code for the above approach
function findMostFrequentPair(nums) {
    let maxFrequency = 0;
    let mostFrequentPair = [];
 
    // Initialize the frequency to 1
    // for the current pair
    for (let i = 0; i < nums.length - 1; i++) {
        let currentPairFrequency = 1;
        for (let j = i + 1; j < nums.length; j++) {
 
            // Increment the
            // frequency if the
            // pair matches.
            if (
                nums[i] == nums[j] &&
                i + 1 < nums.length &&
                j + 1 < nums.length &&
                nums[i + 1] == nums[j + 1]
            ) {
                currentPairFrequency += 1;
            }
        }
 
        if (currentPairFrequency > maxFrequency) {
            maxFrequency = currentPairFrequency;
            mostFrequentPair = [nums[i], nums[i + 1]];
        }
    }
 
    return mostFrequentPair;
}
 
// Drivers code
let arr = [1, 2, 2, 3, 2, 3, 4, 4, 4, 4];
let result = findMostFrequentPair(arr);
 
// Function Call
console.log("Most Frequent Pair: {", result[0], ", ", result[1], "}");


Output

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:

C++




// C++ code for the aboveapproach:
#include <iostream>
#include <unordered_map>
#include <vector>
 
using namespace std;
 
vector<int> findMostFrequentPair(vector<int>& nums)
{
    unordered_map<int, int> pairFrequency;
    int maxFrequency = 0;
    vector<int> mostFrequentPair;
 
    for (int i = 0; i < nums.size() - 1; i++) {
 
        // Combine two adjacent elements
        // into a single integer.
        int currentPair = (nums[i] << 16) | nums[i + 1];
        pairFrequency[currentPair]++;
        if (pairFrequency[currentPair] > maxFrequency) {
            maxFrequency = pairFrequency[currentPair];
            mostFrequentPair = { nums[i], nums[i + 1] };
        }
    }
 
    return mostFrequentPair;
}
 
// Drivers code
int main()
{
    vector<int> arr = { 1, 2, 2, 3, 2, 3, 4, 4, 4, 4 };
    vector<int> result = findMostFrequentPair(arr);
 
    // Function Call
    cout << "Most Frequent Pair: {" << result[0] << ", "
        << result[1] << "}" << endl;
 
    return 0;
}


Java




import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
 
public class Main {
    // Function to find the most frequent pair in an array
    public static List<Integer> findMostFrequentPair(int[] nums) {
        Map<Integer, Integer> pairFrequency = new HashMap<>();
        int maxFrequency = 0;
        List<Integer> mostFrequentPair = new ArrayList<>();
 
        for (int i = 0; i < nums.length - 1; i++) {
            // Combine two adjacent elements into a single integer
            int currentPair = (nums[i] << 16) | nums[i + 1];
            pairFrequency.put(currentPair, pairFrequency.getOrDefault(currentPair, 0) + 1);
 
            if (pairFrequency.get(currentPair) > maxFrequency) {
                maxFrequency = pairFrequency.get(currentPair);
                mostFrequentPair.clear();
                mostFrequentPair.add(nums[i]);
                mostFrequentPair.add(nums[i + 1]);
            }
        }
 
        return mostFrequentPair;
    }
 
    // Driver code
    public static void main(String[] args) {
        int[] arr = {1, 2, 2, 3, 2, 3, 4, 4, 4, 4};
        List<Integer> result = findMostFrequentPair(arr);
 
        // Function Call
        System.out.println("Most Frequent Pair: {" + result.get(0) + ", " + result.get(1) + "}");
    }
}


Python3




def find_most_frequent_pair(nums):
    pair_frequency = {}
    max_frequency = 0
    most_frequent_pair = []
 
    for i in range(len(nums) - 1):
        # Combine two adjacent elements into a single integer
        current_pair = (nums[i] << 16) | nums[i + 1]
        pair_frequency[current_pair] = pair_frequency.get(current_pair, 0) + 1
 
        if pair_frequency[current_pair] > max_frequency:
            max_frequency = pair_frequency[current_pair]
            most_frequent_pair = [nums[i], nums[i + 1]]
 
    return most_frequent_pair
 
# Driver code
arr = [1, 2, 2, 3, 2, 3, 4, 4, 4, 4]
result = find_most_frequent_pair(arr)
 
# Function call
print(f"Most Frequent Pair: {result}")


C#




using System;
using System.Collections.Generic;
 
class Program
{
    static List<int> FindMostFrequentPair(List<int> nums)
    {
        Dictionary<int, int> pairFrequency = new Dictionary<int, int>();
        int maxFrequency = 0;
        List<int> mostFrequentPair = new List<int>();
 
        for (int i = 0; i < nums.Count - 1; i++)
        {
            // Combine two adjacent elements into a single integer.
            int currentPair = (nums[i] << 16) | nums[i + 1];
            if (!pairFrequency.ContainsKey(currentPair))
            {
                pairFrequency[currentPair] = 1;
            }
            else
            {
                pairFrequency[currentPair]++;
            }
 
            if (pairFrequency[currentPair] > maxFrequency)
            {
                maxFrequency = pairFrequency[currentPair];
                mostFrequentPair = new List<int> { nums[i], nums[i + 1] };
            }
        }
 
        return mostFrequentPair;
    }
 
    static void Main()
    {
        List<int> arr = new List<int> { 1, 2, 2, 3, 2, 3, 4, 4, 4, 4 };
        List<int> result = FindMostFrequentPair(arr);
 
        // Function Call
        Console.WriteLine($"Most Frequent Pair: {{{result[0]}, {result[1]}}}");
    }
}


Javascript




function findMostFrequentPair(nums) {
    const pairFrequency = new Map();
    let maxFrequency = 0;
    let mostFrequentPair = [];
 
    for (let i = 0; i < nums.length - 1; i++) {
        // Combine two adjacent elements into a single integer.
        const currentPair = (nums[i] << 16) | nums[i + 1];
        pairFrequency.set(currentPair, (pairFrequency.get(currentPair) || 0) + 1);
 
        if (pairFrequency.get(currentPair) > maxFrequency) {
            maxFrequency = pairFrequency.get(currentPair);
            mostFrequentPair = [nums[i], nums[i + 1]];
        }
    }
 
    return mostFrequentPair;
}
 
// Driver's code
const arr = [1, 2, 2, 3, 2, 3, 4, 4, 4, 4];
const result = findMostFrequentPair(arr);
 
// Function Call
console.log("Most Frequent Pair: {" + result[0] + ", " + result[1] + "}");


Output

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads