Open In App

Print numbers in descending order along with their frequencies

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr, the task is to print the elements of the array in descending order along with their frequencies.
Examples: 
 

Input: arr[] = {1, 3, 3, 3, 4, 4, 5} 
Output: 5 occurs 1 times 
4 occurs 2 times 
3 occurs 3 times 
1 occurs 1 times
Input: arr[] = {1, 1, 1, 2, 3, 4, 9, 9, 10} 
Output: 10 occurs 1 times 
9 occurs 2 times 
4 occurs 1 times 
3 occurs 1 times 
2 occurs 1 times 
1 occurs 3 times 
 

 

Naive approach: Use some Data-Structure (e.g. multiset) that stores elements in decreasing order and then print the elements one by one with its count and then erase it from the Data-structure. The time complexity will be O(N log N) and the auxiliary space will be O(N) for the Data-structure used.
Below is the implementation of the above approach:
 

CPP




// C++ program to print the elements in
// descending along with their frequencies
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the elements in descending
// along with their frequencies
void printElements(int a[], int n)
{
 
    // A multiset to store elements in decreasing order
    multiset<int, greater<int> > ms;
 
    // Insert elements in the multiset
    for (int i = 0; i < n; i++) {
        ms.insert(a[i]);
    }
 
    // Print the elements along with their frequencies
    while (!ms.empty()) {
 
        // Find the maximum element
        int maxel = *ms.begin();
 
        // Number of times it occurs
        int times = ms.count(maxel);
 
        cout << maxel << " occurs " << times << " times\n";
 
        // Erase the maxel
        ms.erase(maxel);
    }
}
 
// Driver Code
int main()
{
    int a[] = { 1, 1, 1, 2, 3, 4, 9, 9, 10 };
    int n = sizeof(a) / sizeof(a[0]);
    printElements(a, n);
    return 0;
}


Python3




# Function to print the elements in descending
# along with their frequencies
def printElements(a):
    # A multiset to store elements in decreasing order
    ms = sorted(a, reverse=True)
 
    # Print the elements along with their frequencies
    while ms:
        # Find the maximum element
        maxel = ms[0]
 
        # Number of times it occurs
        times = ms.count(maxel)
 
        print(f"{maxel} occurs {times} times")
 
        # Remove all occurrences of maxel
        ms = [x for x in ms if x != maxel]
 
# Driver code
if __name__ == '__main__':
    a = [1, 1, 1, 2, 3, 4, 9, 9, 10]
    printElements(a)


Javascript




// JavaScript program to print the elements in
// descending along with their frequencies in reverse order
 
// Function to print the elements in descending
// along with their frequencies in reverse order
function printElements(a) {
 
    // A Map to store elements in decreasing order
    const ms = new Map();
 
    // Insert elements in the Map
    for (let i = 0; i < a.length; i++) {
        const key = a[i];
        ms.set(key, (ms.get(key) || 0) + 1);
    }
 
    // Array to store the elements along with their frequencies
    const elements = [];
 
    // Store the elements and their frequencies in the array
    for (const [key, value] of ms.entries()) {
        elements.push(`${key} occurs ${value} times`);
    }
 
    // Print the elements along with their frequencies in reverse order
    for (let i = elements.length - 1; i >= 0; i--) {
        console.log(elements[i]);
    }
}
 
// Driver Code
const a = [1, 1, 1, 2, 3, 4, 9, 9, 10];
printElements(a);


Java




import java.util.*;
 
public class Main {
     
    // Function to print the elements in descending
    // along with their frequencies
    static void printElements(int[] a, int n) {
         
        // A TreeMap to store elements in decreasing order
        TreeMap<Integer, Integer> tm = new TreeMap<>(Collections.reverseOrder());
         
        // Insert elements in the TreeMap
        for (int i = 0; i < n; i++) {
            if (tm.containsKey(a[i])) {
                tm.put(a[i], tm.get(a[i]) + 1);
            } else {
                tm.put(a[i], 1);
            }
        }
         
        // Print the elements along with their frequencies
        for (Map.Entry<Integer, Integer> entry : tm.entrySet()) {
            int element = entry.getKey();
            int frequency = entry.getValue();
            System.out.println(element + " occurs " + frequency + " times");
        }
    }
     
    // Driver Code
    public static void main(String[] args) {
        int[] a = { 1, 1, 1, 2, 3, 4, 9, 9, 10 };
        int n = a.length;
        printElements(a, n);
    }
}


C#




using System;
using System.Collections.Generic;
 
public class Program {
     
    // Function to print the elements in descending
    // along with their frequencies
    static void PrintElements(int[] a, int n) {
         
        // A SortedDictionary to store elements in decreasing order
        SortedDictionary<int, int> sd = new SortedDictionary<int, int>(new DescendingComparer());
         
        // Insert elements in the SortedDictionary
        for (int i = 0; i < n; i++) {
            if (sd.ContainsKey(a[i])) {
                sd[a[i]]++;
            } else {
                sd[a[i]] = 1;
            }
        }
         
        // Print the elements along with their frequencies
        foreach (KeyValuePair<int, int> entry in sd) {
            int element = entry.Key;
            int frequency = entry.Value;
            Console.WriteLine(element + " occurs " + frequency + " times");
        }
    }
     
    // Custom comparer to sort the keys in descending order
    class DescendingComparer : IComparer<int> {
        public int Compare(int x, int y) {
            return y.CompareTo(x);
        }
    }
     
    // Driver Code
    public static void Main() {
        int[] a = { 1, 1, 1, 2, 3, 4, 9, 9, 10 };
        int n = a.Length;
        PrintElements(a, n);
    }
}


Output: 

10 occurs 1 times
9 occurs 2 times
4 occurs 1 times
3 occurs 1 times
2 occurs 1 times
1 occurs 3 times

 

Time Complexity: O(N*logN), as we are using a loop to traverse N times and in each traversal, we are doing a multiset operation which will cost us logN time.

Auxiliary Space: O(N), as we are using extra space for the multiset.

Efficient Approach: Sort the array in descending order and then start printing the elements from the beginning along with their frequencies.
Below is the implementation of the above approach: 
 

C++




// C++ program to print the elements in
// descending along with their frequencies
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the elements in descending
// along with their frequencies
void printElements(int a[], int n)
{
 
    // Sorts the element in decreasing order
    sort(a, a + n, greater<int>());
    int cnt = 1;
 
    // traverse the array elements
    for (int i = 0; i < n - 1; i++) {
 
        // Prints the number and count
        if (a[i] != a[i + 1]) {
            cout << a[i] << " occurs " << cnt << " times\n";
            cnt = 1;
        }
        else
            cnt += 1;
    }
 
    // Prints the last step
    cout << a[n - 1] << " occurs " << cnt << " times\n";
}
 
// Driver Code
int main()
{
    int a[] = { 1, 1, 1, 2, 3, 4, 9, 9, 10 };
    int n = sizeof(a) / sizeof(a[0]);
 
    printElements(a, n);
    return 0;
}


Java




// Java program to print the elements in
// descending along with their frequencies
import java.util.*;
 
class GFG
{
 
// Function to print the elements in descending
// along with their frequencies
static void printElements(int a[], int n)
{
 
    // Sorts the element in decreasing order
    Arrays.sort(a);
    a = reverse(a);
    int cnt = 1;
 
    // traverse the array elements
    for (int i = 0; i < n - 1; i++)
    {
 
        // Prints the number and count
        if (a[i] != a[i + 1])
        {
            System.out.print(a[i]+ " occurs " +
                            cnt + " times\n");
            cnt = 1;
        }
        else
            cnt += 1;
    }
 
    // Prints the last step
    System.out.print(a[n - 1]+ " occurs " +
                    cnt + " times\n");
}
 
static int[] reverse(int a[])
{
    int i, n = a.length, t;
    for (i = 0; i < n / 2; i++)
    {
        t = a[i];
        a[i] = a[n - i - 1];
        a[n - i - 1] = t;
    }
    return a;
}
 
// Driver Code
public static void main(String[] args)
{
    int a[] = { 1, 1, 1, 2, 3, 4, 9, 9, 10 };
    int n = a.length;
 
    printElements(a, n);
}
}
 
// This code is contributed by PrinciRaj1992


Python3




# Python3 program to print the elements in
# descending along with their frequencies
 
# Function to print the elements in
# descending along with their frequencies
def printElements(a, n) :
 
    # Sorts the element in decreasing order
    a.sort(reverse = True)
    cnt = 1
 
    # traverse the array elements
    for i in range(n - 1) :
 
        # Prints the number and count
        if (a[i] != a[i + 1]) :
            print(a[i], " occurs ", cnt, "times")
            cnt = 1
         
        else :
            cnt += 1
     
    # Prints the last step
    print(a[n - 1], "occurs", cnt, "times")
 
# Driver Code
if __name__ == "__main__" :
 
    a = [ 1, 1, 1, 2,
          3, 4, 9, 9, 10 ]
    n = len(a)
 
    printElements(a, n)
     
# This code is contributed by Ryuga


C#




// C# program to print the elements in
// descending along with their frequencies
using System;
 
class GFG
{
 
// Function to print the elements in descending
// along with their frequencies
static void printElements(int []a, int n)
{
 
    // Sorts the element in decreasing order
    Array.Sort(a);
    a = reverse(a);
    int cnt = 1;
 
    // traverse the array elements
    for (int i = 0; i < n - 1; i++)
    {
 
        // Prints the number and count
        if (a[i] != a[i + 1])
        {
            Console.Write(a[i]+ " occurs " +
                            cnt + " times\n");
            cnt = 1;
        }
        else
            cnt += 1;
    }
 
    // Prints the last step
    Console.Write(a[n - 1]+ " occurs " +
                    cnt + " times\n");
}
 
static int[] reverse(int []a)
{
    int i, n = a.Length, t;
    for (i = 0; i < n / 2; i++)
    {
        t = a[i];
        a[i] = a[n - i - 1];
        a[n - i - 1] = t;
    }
    return a;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []a = { 1, 1, 1, 2, 3, 4, 9, 9, 10 };
    int n = a.Length;
 
    printElements(a, n);
}
}
 
// This code is contributed by PrinciRaj1992


PHP




<?php
// PHP program to print the elements in
// descending along with their frequencies
 
// Function to print the elements in
// descending along with their frequencies
function printElements(&$a, $n)
{
 
    // Sorts the element in
    // decreasing order
    rsort($a);
    $cnt = 1;
 
    // traverse the array elements
    for ($i = 0; $i < $n - 1; $i++)
    {
 
        // Prints the number and count
        if ($a[$i] != $a[$i + 1])
        {
            echo ($a[$i]);
            echo (" occurs " );
            echo $cnt ;
            echo (" times\n");
            $cnt = 1;
        }
        else
            $cnt += 1;
    }
 
    // Prints the last step
    echo ($a[$n - 1]);
    echo (" occurs ");
    echo $cnt;
    echo (" times\n");
}
 
// Driver Code
$a = array(1, 1, 1, 2, 3,
           4, 9, 9, 10 );
$n = sizeof($a);
 
printElements($a, $n);
 
// This code is contributed
// by Shivi_Aggarwal
?>


Javascript




<script>
 
// javascript program to print the elements in
// descending along with their frequencies
 
   
// Function to print the elements in descending
// along with their frequencies
  function printElements(a,  n)
   
{
   
    // Sorts the element in decreasing order
    a=a.sort(compare);
    a = reverse(a);
    var cnt = 1;
   
    // traverse the array elements
    for (var i = 0; i < n - 1; i++)
    {
   
        // Prints the number and count
        if (a[i] != a[i + 1])
        {
            document.write(a[i]+ " occurs " +   cnt + " times" + "<br>");
            cnt = 1;
        }
        else
            cnt += 1;
    }
   
    // Prints the last step
    document.write(a[n - 1]+ " occurs " + cnt + " times" + "<br>");
}
   
  function reverse(a){
    var i, n = a.length, t;
     
    for (i = 0; i < n / 2; i++)
    {
        t = a[i];
        a[i] = a[n - i - 1];
        a[n - i - 1] = t;
    }
    return a;
}
 
function compare(a, b) {
    if (a < b) {
        return -1;
    } else if (a > b) {
        return 1;
    } else {
        return 0;
    }
}
   
// Driver Code
 
    var a = [ 1, 1, 1, 2, 3, 4, 9, 9, 10 ];
    var n = a.length;
   
    printElements(a, n);
  
 // This code is contributed by bunnyram19.
</script>


Output: 

10 occurs 1 times
9 occurs 2 times
4 occurs 1 times
3 occurs 1 times
2 occurs 1 times
1 occurs 3 times

 

Time Complexity: O(N*logN), as we are using the sort function which will cost us O(N*logN) time.

Auxiliary Space: O(1), as we are not using any extra space.



Similar Reads

Sort all even numbers in ascending order and then sort all odd numbers in descending order
Given an array of integers (both odd and even), sort them in such a way that the first part of the array contains odd numbers sorted in descending order, rest portion contains even numbers sorted in ascending order.Examples: Input: arr[] = {1, 2, 3, 5, 4, 7, 10}Output: arr[] = {7, 5, 3, 1, 2, 4, 10} Input: arr[] = {0, 4, 5, 3, 7, 2, 1}Output: arr[]
25 min read
Print 2-D co-ordinate points in ascending order followed by their frequencies
Given two arrays x[] and y[] where x[i] represents the x coordinate and y[i] represent the corresponding y coordinate of a 2-D point, the task is to print the coordinate points in ascending order followed by their frequencies.Examples: Input: x[] = {1, 2, 1, 1, 1}, y[] = {1, 1, 3, 1, 3} Output: 1 1 2 1 3 2 2 1 1Input: x[] = {-1, 2, 1, -1, 2}, y[] =
5 min read
Print characters and their frequencies in order of occurrence using a LinkedHashMap in Java
Given a string str containing only lowercase characters. The task is to print the characters along with their frequencies in the order of their occurrence in the given string.Examples: Input: str = "geeksforgeeks" Output: g2 e4 k2 s2 f1 o1 r1Input: str = "helloworld" Output: h1 e1 l3 o2 w1 r1 d1 Approach: Traverse the given string character by char
2 min read
Print characters and their frequencies in order of occurrence using Binary Tree
Given a string str containing only lowercase characters. The problem is to print the characters along with their frequency in the order of their occurrence using Binary TreeExamples: Input: str = "aaaabbnnccccz" Output: "a4b2n2c4z" Explanation: Input: str = "geeksforgeeks" Output: g2e4k2s2for Approach: Start with the first character in the string.P
14 min read
Print characters and their frequencies in order of occurrence
Given string str containing only lowercase characters. The problem is to print the characters along with their frequency in the order of their occurrence and in the given format explained in the examples below. Examples: Input : str = "geeksforgeeks" Output : g2 e4 k2 s2 f1 o1 r1 Input : str = "elephant" Output : e2 l1 p1 h1 a1 n1 t1 Source: SAP In
19 min read
Sort Array according to modulus of their values with their frequencies
Given an array arr containing N positive integers, sort them according to the increasing modulus of their values with their frequencies. Example: Input: arr[]={1, 1, 5, 3, 2, 3, 3, 3, 4, 5, 4, 5}Output: 2 4 4 1 1 5 5 5 3 3 3 3 Explanation:The elements are sorted in the following order:2 % frequency(2) = 2 % 1 = 04 % frequency(4) = 4 % 2 = 01 % freq
6 min read
Sorting rows of matrix in ascending order followed by columns in descending order
Given a matrix, sort the rows of matrix in ascending order followed by sorting the columns in descending order. Examples : Input : a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Output : 7 8 9 4 5 6 1 2 3 Input : a[3][3] = {{3, 2, 1}, {9, 8, 7}, {6, 5, 4}}; Output : 7 8 9 4 5 6 1 2 3 Approach: Traverse all rows one by one and sort rows in ascending o
10 min read
Sort first k values in ascending order and remaining n-k values in descending order
Given an array of size n, arrange the first k elements of the array in ascending order and the remaining n-k elements in descending order. Examples: Input: arr[] = {5, 4, 6, 2, 1, 3, 8, 9, -1}, k = 4 Output: 2 4 5 6 9 8 3 1 -1 Input: arr[] = {5, 4, 6}, k = 2 Output: 4 5 6 Algorithm: Store the first k elements in an array and sort that in ascending
11 min read
Sorting rows of matrix in descending order followed by columns in ascending order
Given a matrix of distinct elements. The task is to sort the rows of matrix in descending order followed by sorting the columns in ascending order. Examples: Input: a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Output: 3 2 1 6 5 4 9 8 7 Input: a[3][3] = {{3, 2, 1}, {9, 8, 7}, {6, 5, 4}}; Output: 3 2 1 6 5 4 9 8 7 Approach: Traverse all rows one by o
9 min read
Sort an array of strings in ascending order with each string sorted in descending order
Given a array of strings S[] of size N (1 ? N ? 105), sort characters of each string in descending order and then print the array of strings in ascending order. Examples: Input: s[] = {"apple", "box", "cat"} Output: pplea tca xob Explanation: Sorting each string in descending order, S[] modifies to {"pplea", "xob", "tca"}. Sorting the array in asce
9 min read