(Translated by https://www.hiragana.jp/)
Most frequent element in an array - GeeksforGeeks
Open In App

Most frequent element in an array

Last Updated : 13 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array, find the most frequent element in it. If there are multiple elements that appear a maximum number of times, print any one of them.

Examples: 

Input : arr[] = {1, 3, 2, 1, 4, 1}
Output : 1
Explanation: 1 appears three times in array which is maximum frequency.

Input : arr[] = {10, 20, 10, 20, 30, 20, 20}
Output : 20 appears four times in array which is maximum frequency

Naive Approach

The naive approach involves using two nested loops: the outer loop picks each element, and the inner loop counts the frequency of the picked element. This method is straightforward but inefficient.

C++
// CPP program to find the most frequent element in an array.

#include <bits/stdc++.h>

using namespace std;

int mostFrequent(int* arr, int n)
{
    int maxcount = 0;
    int element_having_max_freq;
    for (int i = 0; i < n; i++) {
        int count = 0;
        for (int j = 0; j < n; j++) {
            if (arr[i] == arr[j])
                count++;
        }

        if (count > maxcount) {
            maxcount = count;
            element_having_max_freq = arr[i];
        }
    }

    return element_having_max_freq;
}

// Driver program
int main()
{
    int arr[] = { 40, 50, 30, 40, 50, 30, 30 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << mostFrequent(arr, n);
    return 0;
}
Java
// Java program to find the most frequent element
// in an array.

public class GFG
{
  public static int mostFrequent(int[] arr, int n)
  {
    int maxcount = 0;
    int element_having_max_freq = 0;
    for (int i = 0; i < n; i++) {
      int count = 0;
      for (int j = 0; j < n; j++) {
        if (arr[i] == arr[j]) {
          count++;
        }
      }

      if (count > maxcount) {
        maxcount = count;
        element_having_max_freq = arr[i];
      }
    }

    return element_having_max_freq;
  }

  // Driver program
  public static void main(String[] args)
  {
    int[] arr = { 40, 50, 30, 40, 50, 30, 30 };
    int n = arr.length;
    System.out.print(mostFrequent(arr, n));
  }
}
Python
# Python3 program to find the most
# frequent element in an array.
def mostFrequent(arr, n):
  maxcount = 0;
  element_having_max_freq = 0;
  for i in range(0, n):
    count = 0
    for j in range(0, n):
      if(arr[i] == arr[j]):
        count += 1
    if(count > maxcount):
      maxcount = count
      element_having_max_freq = arr[i]
  
  return element_having_max_freq;

# Driver Code
arr = [40,50,30,40,50,30,30]
n = len(arr)
print(mostFrequent(arr, n))
C#
// C# program to find the most frequent element
// in an array
using System;
public class GFG
{
  
  // C# program to find the most frequent element
  // in an array.
  public static int mostFrequent(int[] arr, int n)
  {
    int maxcount = 0;
    int element_having_max_freq = 0;
    for (int i = 0; i < n; i++) {
      int count = 0;
      for (int j = 0; j < n; j++) {
        if (arr[i] == arr[j]) {
          count++;
        }
      }

      if (count > maxcount) {
        maxcount = count;
        element_having_max_freq = arr[i];
      }
    }

    return element_having_max_freq;
  }

  // Driver program
  public static void Main(String[] args)
  {
    int[] arr = { 40, 50, 30, 40, 50, 30, 30 };
    int n = arr.Length;
    Console.Write(mostFrequent(arr, n));
  }
}
JavaScript
// JavaScript program to find the most frequent element in an array
function mostFrequent(arr, n) {
    let maxcount = 0;
    let element_having_max_freq;

    for (let i = 0; i < n; i++) {
        let count = 0;

        for (let j = 0; j < n; j++) {
            if (arr[i] == arr[j]) {
                count++;
            }
        }

        if (count > maxcount) {
            maxcount = count;
            element_having_max_freq = arr[i];
        }
    }

    return element_having_max_freq;
}

// Driver Code
let arr = [40, 50, 30, 40, 50, 30, 30];
let n = arr.length;
console.log(mostFrequent(arr, n));

Output
30

Time complexity: O(n2) since 2 loops are running from i=0 to i=n we can improve its time complexity by taking a visited  array and skipping numbers for which we already calculated the frequency.
Auxiliary space: O(1) as it is using constant space for variables

Using Sorting

This method sorts the array first and then finds the maximum frequency by linearly traversing the sorted array. Sorting brings similar elements next to each other, making frequency counting easier.

C++
// CPP program to find the most frequent element
// in an array.
#include <bits/stdc++.h>
using namespace std;

int mostFrequent(int arr[], int n)
{
    // Sort the array
    sort(arr, arr + n);

    // Find the max frequency using linear traversal
    int max_count = 1, res = arr[0], curr_count = 1;
    for (int i = 1; i < n; i++) {
        if (arr[i] == arr[i - 1])
            curr_count++;
        else
            curr_count = 1;
      
        if (curr_count > max_count) {
            max_count = curr_count;
            res = arr[i - 1];
        }
    }

    return res;
}

// Driver program
int main()
{
    int arr[] = { 40,50,30,40,50,30,30};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << mostFrequent(arr, n);
    return 0;
}
C
// CPP program to find the most frequent element
// in an array.
#include <stdio.h>
#include <stdlib.h>

int cmpfunc(const void* a, const void* b)
{
    return (*(int*)a - *(int*)b);
}

int mostFrequent(int arr[], int n)
{
    // Sort the array
    qsort(arr, n, sizeof(int), cmpfunc);

    // find the max frequency using linear traversal
    int max_count = 1, res = arr[0], curr_count = 1;
     for (int i = 1; i < n; i++) {
        if (arr[i] == arr[i - 1])
            curr_count++;
        else
            curr_count = 1;
      
        if (curr_count > max_count) {
            max_count = curr_count;
            res = arr[i - 1];
        }
    }
  
    return res;
}

// driver program
int main()
{
    int arr[] = { 40,50,30,40,50,30,30};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d", mostFrequent(arr, n));
    return 0;
}
Java
// Java program to find the most frequent element
// in an array
import java.util.*;

class GFG {

    static int mostFrequent(int arr[], int n)
    {
        // Sort the array
        Arrays.sort(arr);

        // find the max frequency using linear traversal
        int max_count = 1, res = arr[0];
        int curr_count = 1;

        for (int i = 1; i < n; i++) {
            if (arr[i] == arr[i - 1])
                curr_count++;
            else
                curr_count = 1;

            if (curr_count > max_count) {
                max_count = curr_count;
                res = arr[i - 1];
            }
        }
        return res;
    }

    // Driver program
    public static void main(String[] args)
    {
        int arr[] = { 40,50,30,40,50,30,30};
        int n = arr.length;
        System.out.println(mostFrequent(arr, n));
    }
}
Python
# Python3 program to find the most
# frequent element in an array.


def mostFrequent(arr, n):

    # Sort the array
    arr.sort()

    # find the max frequency using
    # linear traversal
    max_count = 1
    res = arr[0]
    curr_count = 1

    for i in range(1, n):
        if (arr[i] == arr[i - 1]):
            curr_count += 1
        else:
            curr_count = 1

         # If last element is most frequent
        if (curr_count > max_count):
            max_count = curr_count
            res = arr[i - 1]

    return res


# Driver Code
arr = [40,50,30,40,50,30,30]
n = len(arr)
print(mostFrequent(arr, n))
C#
// C# program to find the most
// frequent element in an array
using System;

class GFG {

    static int mostFrequent(int[] arr, int n)
    {

        // Sort the array
        Array.Sort(arr);

        // find the max frequency using
        // linear traversal
        int max_count = 1, res = arr[0];
        int curr_count = 1;

        for (int i = 1; i < n; i++) {
            if (arr[i] == arr[i - 1])
                curr_count++;
            else
                curr_count = 1;

            // If last element is most frequent
            if (curr_count > max_count) {
                max_count = curr_count;
                res = arr[i - 1];
            }
        }

        return res;
    }

    // Driver code
    public static void Main()
    {

        int[] arr = {40,50,30,40,50,30,30 };
        int n = arr.Length;

        Console.WriteLine(mostFrequent(arr, n));
    }
}
JavaScript
// JavaScript program to find the most frequent element
// in an array

function mostFrequent(arr, n)
{

    // Sort the array
    arr.sort();

    // find the max frequency using linear
    // traversal
    let max_count = 1, res = arr[0];
    let curr_count = 1;

    for (let i = 1; i < n; i++) {
        if (arr[i] == arr[i - 1])
            curr_count++;
        else
            curr_count = 1;

        if (curr_count > max_count) {
            max_count = curr_count;
            res = arr[i - 1];
        }
    }

    return res;
}

let arr = [ 40, 50, 30, 40, 50, 30, 30 ];
let n = arr.length;
console.log(mostFrequent(arr, n));
PHP
<?php
// PHP program to find the
// most frequent element
// in an array.

function mostFrequent( $arr, $n)
{
    
    // Sort the array
    sort($arr);
    sort($arr , $n);

    // find the max frequency 
    // using linear traversal
    $max_count = 1; 
    $res = $arr[0]; 
    $curr_count = 1;
    for ($i = 1; $i < $n; $i++) 
    {
        if ($arr[$i] == $arr[$i - 1])
            $curr_count++;
        else
              $curr_count = 1;
       
         if ($curr_count > $max_count)
         {
              $max_count = $curr_count;
              $res = $arr[$i - 1];
          }
    }

    return $res;
}

// Driver Code
{
    $arr = array(40,50,30,40,50,30,30);
    $n = sizeof($arr) / sizeof($arr[0]);
    echo mostFrequent($arr, $n);
    return 0;
}

// This code is contributed by nitin mittal
?>

Output
30

Time Complexity: O(nlog(n)) 
Auxiliary Space: O(1)

Using Hashing

Using a hash table, this approach stores each element’s frequency and then finds the element with the maximum frequency. This method is efficient in terms of both time and space. 

C++
// CPP program to find the most frequent element
// in an array.
#include <bits/stdc++.h>
using namespace std;

int mostFrequent(int arr[], int n)
{
    // Insert all elements in hash.
    unordered_map<int, int> hash;
    for (int i = 0; i < n; i++)
        hash[arr[i]]++;

    // find the max frequency
    int max_count = 0, res = -1;
    for (auto i : hash) {
        if (max_count < i.second) {
            res = i.first;
            max_count = i.second;
        }
    }

    return res;
}

int main()
{
    int arr[] = {40,50,30,40,50,30,30 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << mostFrequent(arr, n);
    return 0;
}
Java
// Java program to find the most frequent element
// in an array
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

class GFG {

    static int mostFrequent(int arr[], int n)
    {

        // Insert all elements in hash
        Map<Integer, Integer> hp
            = new HashMap<Integer, Integer>();

        for (int i = 0; i < n; i++) {
            int key = arr[i];
            if (hp.containsKey(key)) {
                int freq = hp.get(key);
                freq++;
                hp.put(key, freq);
            }
            else {
                hp.put(key, 1);
            }
        }

        // find max frequency.
        int max_count = 0, res = -1;

        for (Entry<Integer, Integer> val : hp.entrySet()) {
            if (max_count < val.getValue()) {
                res = val.getKey();
                max_count = val.getValue();
            }
        }

        return res;
    }

    public static void main(String[] args)
    {

        int arr[] = { 40, 50, 30, 40, 50, 30, 30 };
        int n = arr.length;

        System.out.println(mostFrequent(arr, n));
    }
}
Python
# Python3 program to find the most 
# frequent element in an array.
import math as mt

def mostFrequent(arr, n):

    # Insert all elements in Hash.
    Hash = dict()
    for i in range(n):
        if arr[i] in Hash.keys():
            Hash[arr[i]] += 1
        else:
            Hash[arr[i]] = 1

    # find the max frequency
    max_count = 0
    res = -1
    for i in Hash: 
        if (max_count < Hash[i]): 
            res = i
            max_count = Hash[i]
        
    return res
  
arr = [ 40,50,30,40,50,30,30] 
n = len(arr)
print(mostFrequent(arr, n))
C#
// C# program to find the most 
// frequent element in an array
using System;
using System.Collections.Generic;

class GFG
{
    static int mostFrequent(int []arr, 
                            int n)
    {
        // Insert all elements in hash
        Dictionary<int, int> hp = 
                    new Dictionary<int, int>();
        
        for (int i = 0; i < n; i++)
        {
            int key = arr[i];
            if(hp.ContainsKey(key))
            {
                int freq = hp[key];
                freq++;
                hp[key] = freq;
            }
            else
                hp.Add(key, 1);
        }
        
        // find max frequency.
        int min_count = 0, res = -1;
        
        foreach (KeyValuePair<int, 
                    int> pair in hp)
        {
            if (min_count < pair.Value)
            {
                res = pair.Key;
                min_count = pair.Value;
            }
        } 
        return res;
    }
    
    static void Main ()
    {
        int []arr = new int[]{40,50,30,40,50,30,30};
        int n = arr.Length;
        
        Console.Write(mostFrequent(arr, n));
    }
}
JavaScript
// Javascript program to find
// the most frequent element
// in an array.

function mostFrequent(arr, n)
{
    // Insert all elements in hash.
    var hash = new Map();
    for (var i = 0; i < n; i++) {
        if (hash.has(arr[i]))
            hash.set(arr[i], hash.get(arr[i]) + 1)
            else hash.set(arr[i], 1)
    }

    // find the max frequency
    var max_count = 0, res = -1;
    hash.forEach((value, key) => {
        if (max_count < value) {
            res = key;
            max_count = value;
        }
    });

    return res;
}

var arr = [ 40, 50, 30, 40, 50, 30, 30 ];
var n = arr.length;
console.log(mostFrequent(arr, n));

Output
30

Time Complexity: O(n) 
Auxiliary Space: O(n)

Using Moore’s Voting Algorithm

Moore’s Voting Algorithm is a space-efficient algorithm that works well when the most frequent element (or majority element) occurs more than [Tex]n/2[/Tex] times. It finds the majority element by counting votes. However, this algorithm only guarantees correctness if there is an element that occurs more than [Tex]n/2[/Tex] times.

C++
#include <iostream>
using namespace std;

int findCandidate(int *arr, int n)
{
    int res = 0;
    int count = 1;
    for (int i = 1; i < n; i++)
    {
        if (arr[i] == arr[res])
        {
            count++;
        }
        else
        {
            count--;
        }

        if (count == 0)
        {
            res = i;
            count = 1;
        }
    }
    return arr[res];
}

bool isMajority(int *arr, int n, int candidate)
{
    int count = 0;
    for (int i = 0; i < n; i++)
    {
        if (arr[i] == candidate)
            count++;
    }
    return count > n / 2;
}

int main()
{
    int arr[] = {30, 30, 30, 40, 50, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);
    int candidate = findCandidate(arr, n);
    if (isMajority(arr, n, candidate))
    {
        cout << "Element " << candidate << " occurs more than " << n / 2 << " times" << endl;
    }
    else
    {
        cout << "No element occurs more than " << n / 2 << " times" << endl;
    }
    return 0;
}
Java
import java.io.*;

class GFG {

    static int findCandidate(int[] arr, int n)
    {
        // using moore's voting algorithm to find the
        // candidate
        int res = 0;
        int count = 1;
        for (int i = 1; i < n; i++) {
            if (arr[i] == arr[res]) {
                count++;
            }
            else {
                count--;
            }

            if (count == 0) {
                res = i;
                count = 1;
            }
        }
        return arr[res];
    }

    static boolean isMajority(int[] arr, int n,
                              int candidate)
    {
        // check if candidate is actually the majority
        // element
        int count = 0;
        for (int i = 0; i < n; i++) {
            if (arr[i] == candidate) {
                count++;
            }
        }
        return count > n / 2;
    }

    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 30, 30, 30, 40, 50, 40, 50 };
        int n = arr.length;
        int candidate = findCandidate(arr, n);
        if (isMajority(arr, n, candidate)) {
            System.out.println("Element " + candidate
                               + " occurs more than "
                               + n / 2 + " times");
        }
        else {
            System.out.println(
                "No element occurs more than " + n / 2
                + " times");
        }
    }
}
C#
using System;

class GFG {

    static int FindCandidate(int[] arr, int n)
    {
        // using moore's voting algorithm to find the
        // candidate
        int res = 0;
        int count = 1;
        for (int i = 1; i < n; i++) {
            if (arr[i] == arr[res]) {
                count++;
            }
            else {
                count--;
            }

            if (count == 0) {
                res = i;
                count = 1;
            }
        }
        return arr[res];
    }

    static bool IsMajority(int[] arr, int n, int candidate)
    {
        // check if candidate is actually the majority
        // element
        int count = 0;
        for (int i = 0; i < n; i++) {
            if (arr[i] == candidate) {
                count++;
            }
        }
        return count > n / 2;
    }

    // Driver code
    public static void Main(string[] args)
    {
        int[] arr = { 30, 30, 30, 40, 50, 40, 50 };
        int n = arr.Length;
        int candidate = FindCandidate(arr, n);
        if (IsMajority(arr, n, candidate)) {
            Console.WriteLine("Element " + candidate
                              + " occurs more than " + n / 2
                              + " times");
        }
        else {
            Console.WriteLine("No element occurs more than "
                              + n / 2 + " times");
        }
    }
}

// This code is contributed by Mohammed Raziullah Ansari
JavaScript
function findCandidate(arr, n)
{
    // using moore's voting algorithm to find the candidate
    var res = 0;
    var count = 1;
    for (var i = 1; i < n; i++) {
        if (arr[i] === arr[res]) {
            count++;
        }
        else {
            count--;
        }

        if (count === 0) {
            res = i;
            count = 1;
        }
    }
    return arr[res];
}

function isMajority(arr, n, candidate)
{
    // check if candidate is actually the majority element
    var count = 0;
    for (var i = 0; i < n; i++) {
        if (arr[i] === candidate) {
            count++;
        }
    }
    return count > n / 2;
}

var arr = [ 30, 30, 30, 40, 50, 40, 50 ];
var n = arr.length;
var candidate = findCandidate(arr, n);
if (isMajority(arr, n, candidate)) {
    console.log("Element " + candidate
                   + " occurs more than " + n / 2 + " times");
}
else {
    console.log("No element occurs more than " + n / 2 + " times" );
}

Output
Element 30 occurs 3 times

Time Complexity: O(n)
Auxiliary Space: O(1)

Note: Moore’s Voting Algorithm correctly identifies the majority element only if such an element exists. In cases where no element occurs more than n/2 times, the algorithm may produce an incorrect result.



Previous Article
Next Article

Similar Reads

Minimum distance between any most frequent and least frequent element of an array
Given an integer array arr[] of size N, the task is to find the minimum distance between any most and least frequent element of the given array. Examples: Input: arr[] = {1, 1, 2, 3, 2, 3, 3}Output: 1Explanation: The least frequent elements are 1 and 2 which occurs at indexes: 0, 1, 2, 4. Whereas, the most frequent element is 3 which occurs at inde
13 min read
Generate an array consisting of most frequent greater elements present on the right side of each array element
Given an array A[] of size N, the task is to generate an array B[] based on the following conditions: For every array element A[i], find the most frequent element greater than A[i] present on the right of A[i]. Insert that element into B[].If more than one such element is present on the right, choose the element having the smallest value.If no elem
9 min read
Check if most frequent element in Linked list is divisible by smallest element
Given a Linked list, the task is to check if the most frequently occurring element in the linked list is divisible by the smallest element in the linked list. If divisible then return true otherwise return false. Note: If there is more than one mode then take the greater mode. Examples: Input: Linked List: 4 -> 2 -> 1 -> 3 -> 3 -> 3O
7 min read
Most frequent element in Array after replacing given index by K for Q queries
Given an array arr[] of size N, and Q queries of the form {i, k} for which, the task is to print the most frequent element in the array after replacing arr[i] by k.Example : Input: arr[] = {2, 2, 2, 3, 3}, Query = {{0, 3}, {4, 2}, {0, 4}} Output: 3 2 2 First query: Setting arr[0] = 3 modifies arr[] = {3, 2, 2, 3, 3}. So, 3 has max frequency. Second
10 min read
Remove an occurrence of most frequent array element exactly K times
Given an array arr[], the task is to remove an occurrence of the most frequent array element exactly K times. If multiple array elements have maximum frequency, remove the smallest of them. Print the K deleted elements. Examples: Input: arr[] = {1, 3, 2, 1, 4, 1}, K = 2Output: 1 1Explanation: The frequency of 1 is 3 and frequencies of 2, 3, 4 are 1
12 min read
Find the most frequent element K positions apart from X in given Array
Given an array nums[], and integer K and X, the task is to find the most frequent element K positions away from X in the given array. Examples: Input: nums = [1, 100, 200, 1, 100], K = 1, X = 1Output: 100Explanation: Elements 1 position apart from 1 is only 100.So the answer is 100. Input: nums = [2, 2, 2, 2, 3], K = 2, X = 2Output: X = 2 occurs in
6 min read
Find given occurrences of Mth most frequent element of Array
Given an array arr[], integer M and an array query[] containing Q queries, the task is to find the query[i]th occurrence of Mth most frequent element of the array. Examples: Input: arr[] = {1, 2, 20, 8, 8, 1, 2, 5, 8, 0, 6, 8, 2}, M = 1, query[] = {100, 4, 2}Output: -1, 12, 5Explanation: Here most frequent Integer = 8, with frequency = 4Thus for Qu
9 min read
Queries to insert, delete one occurrence of a number and print the least and most frequent element
Given Q queries of type 1, 2, 3 and 4 as described below. Type-1: Insert a number to the list.Type-2: Delete only one occurrence of a number if exists.Type-3: Print the least frequent element, if multiple elements exist then print the greatest among them.Type-4: Print the most frequent element, if multiple elements exist then print the smallest amo
14 min read
Count of subarrays with X as the most frequent element, for each value of X from 1 to N
Given an array arr[] of size N, (where 0<A[i]<=N, for all 0<=i<N), the task is to calculate for each number X from 1 to N, the number of subarrays in which X is the most frequent element. In subarrays, where more than one element has the maximum frequency, the smallest element should be considered as the most frequent. Examples: Input:
7 min read
Smallest subarray with all occurrences of a most frequent element
Given an array, A. Let x be an element in the array. x has the maximum frequency in the array. Find the smallest subsegment of the array which also has x as the maximum frequency element. Examples: Input : arr[] = {4, 1, 1, 2, 2, 1, 3, 3} Output : 1, 1, 2, 2, 1 The most frequent element is 1. The smallest subarray that has all occurrences of it is
8 min read
Find the most Frequent adjacent Element pairs
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 t
9 min read
Check if the sum of K least and most frequent array elements are equal or not
Given an array arr[] consisting of N integers, the task is to check if the sum of K most frequent array elements and the sum of K least frequent array elements in the array arr[] are equal or not. If found to be true, then print Yes. Otherwise, print No. Examples: Input: arr[] = { 3, 2, 1, 2, 3, 3, 4 }, K=2Output: YesExplanation:The frequency of ea
10 min read
Find the most frequent digit without using array/string
Given an integer, find the most occurring digit in it. If two or more digits occur same number of times, then return the highest of them. Input integer is given as an int variable, not as a string or array. Use of hash or array or string is not allowed. Example: Input: x = 12234Output: The most frequent digit is 2Input: x = 1223377Output: The most
10 min read
Most frequent word in an array of strings
Given an array of words arr[], The task is to find the most occurring word in arr[]. Examples: Input : arr[] = {"geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks"}Output : geeks Explanation : "geeks" is the most frequent word in the given array occurring 3 ti
15+ min read
Most frequent word in first String which is not present in second String
Given two string 'S1' and 'S2', the task is to return the most frequent (which is used the maximum number of times) word from 'S1' that is not present in 'S2'. If more than one word is possible then print lexicographically smallest among them. Examples: Input: S1 = "geeks for geeks is best place to learn", S2 = "bad place" Output: geeks "geeks" is
7 min read
Most frequent factor in a range of integers
You are given a range of numbers, from lower number to higher number (both inclusive). Consider all the factors of these numbers except 1, the task is to find the factor which appears the maximum number of times. If more than one number have maximum frequency then print anyone of them.Examples: Input : lower=10 higher=14 Output : The factor with ma
4 min read
Count of substrings having the most frequent character in the string as first character
Given a string S consisting of lowercase alphabets of size N, the task is to count all substrings which contain the most frequent character in the string as the first character. Note: If more than one character has a maximum frequency, consider the lexicographically smallest among them. Examples: Input: S = "abcab"Output: 7Explanation:There are two
7 min read
Most Frequent Subtree Sum from a given Binary Tree
Given a Binary Tree, the task is to find the most frequent subtree sum that can be obtained by considering every node of the given tree as the root of the subtree. If more than one such sums exist, then print all of them. Examples: Input: 5 / \ 2 -4 Output: 2 -4 3Explanation:The sum of nodes considering 5 as the root of subtree is 5 + 2 - 4 = 3.The
13 min read
Most frequent character in a string after replacing all occurrences of X in a Binary String
Given a string S of length N consisting of 1, 0, and X, the task is to print the character ('1' or '0') with the maximum frequency after replacing every occurrence of X as per the following conditions: If the character present adjacently to the left of X is 1, replace X with 1.If the character present adjacently to the right of X is 0, replace X wi
15+ min read
Find most frequent value of ancestors for each Node of given Tree
Given a tree with N vertices from 0 to N-1 (0th node is root) and val[] where val[i] denotes the value of the ith vertex. The task is to find the array of integers ans[] of length N, where ans[i] denotes the mode value of all its ancestors' values including ith vertex. Note: Mode is the value that has the highest frequency in a given set of values(
10 min read
Program to find second most frequent character
Given a string, find the second most frequent character in it. Expected time complexity is O(n) where n is the length of the input string. Examples: Input: str = "aabababa"; Output: Second most frequent character is 'b' Input: str = "geeksforgeeks"; Output: Second most frequent character is 'g' Input: str = "geeksquiz"; Output: Second most frequent
12 min read
Find the k most frequent words from a file
Given a book of words. Assume you have enough main memory to accommodate all words. design a data structure to find top K maximum occurring words. The data structure should be dynamic so that new words can be added. A simple solution is to use Hashing. Hash all words one by one in a hash table. If a word is already present, then increment its count
15+ min read
Find top k (or most frequent) numbers in a stream
Given an array of n numbers. Your task is to read numbers from the array and keep at-most K numbers at the top (According to their decreasing frequency) every time a new number is read. We basically need to print top k numbers sorted by frequency when input stream has included k distinct elements, else need to print all distinct elements sorted by
11 min read
k most frequent in linear time
Given an array of integers, we need to print k most frequent elements. If there is a tie, we need to prefer the elements whose first appearance is first. Examples: Input : arr[] = {10, 5, 20, 5, 10, 10, 30}, k = 2 Output : 10 5 Input : arr[] = {7, 7, 6, 6, 6, 7, 5, 4, 4, 10, 5}, k = 3 Output : 7 6 5 Explanation : In this example, 7 and 6 have the s
12 min read
Least frequent element in an array
Given an array, find the least frequent element in it. If there are multiple elements that appear least number of times, print any one of them. Examples : Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1}Output : 3Explanation: 3 appears minimum number of times in given array. Input : arr[] = {10, 20, 30}Output : 10 or 20 or 30 A simple solution is to run tw
12 min read
Javascript Program for Least frequent element in an array
Given an array, find the least frequent element in it. If there are multiple elements that appear least number of times, print any one of them. Examples : Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1}Output : 33 appears minimum number of times in givenarray.Input : arr[] = {10, 20, 30}Output : 10 or 20 or 30A simple solution is to run two loops. The out
3 min read
Maximize element at index K in an array with at most sum M and difference between adjacent elements at most 1
Given a positive integer N, the task is to construct an array of length N and find the maximum value at index K such that the sum of all the array elements is at most M and the absolute difference between any two consecutive array elements is at most 1. Examples: Input: N = 3, M = 7, K = 1Output: 3Explanation: According to the given constraints, th
6 min read
Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element
Given an array arr[] consisting of N integers, the task is to find the remaining array element after subtracting each element from its next adjacent element and removing the last array element repeatedly. Examples: Input: arr[] = {3, 4, 2, 1}Output: 4Explanation:Operation 1: The array arr[] modifies to {4 - 3, 2 - 4, 1 - 2} = {1, -2, -1}.Operation
8 min read
Difference between sum of odd and even frequent elements in an Array
Given an array arr[] of integers, the task is to find the absolute difference between the sum of all odd frequent array elements and the sum of all even frequent array elements. Examples: Input: arr[] = {1, 5, 5, 2, 4, 3, 3} Output: 9 Explanation: The even frequent elements are 5 and 3 (both occurring twice). Therefore, sum of all even frequent ele
12 min read
POTD Solutions | 05 Nov’ 23 | Top K Frequent Elements in Array
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Heaps but will also help you build up problem-solving skills. We recommend you to try this problem on our
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg