Cumulative frequency of each element in an array (original) (raw)

Last Updated : 4 Jun, 2026

Given an array **arr[] of elements, the task is to calculate the **cumulative frequency of each distinct element of the array.

**Examples:

**Input: arr[] = [1, 2, 2, 1, 3, 4]
**Output: [2, 4, 5, 6]
**Explanation: The elements are first counted for their frequencies, resulting in {1: 2, 2: 2, 3: 1, 4: 1}. These elements are then sorted by their value, yielding the order [1, 2, 3, 4]. The cumulative frequencies are calculated by adding up the frequencies of the elements as we progress through the sorted order. Thus, the output is [2, 4, 5, 6], representing the cumulative count of elements in the sorted order.

**Input: arr[] = [1, 1, 1, 2, 2, 2]
**Output: [3, 6]
**Explanation: Frequencies are: 1 -> 3 and 2 -> 3. Adding these frequencies cumulatively gives: 3 for element 1 and 3 + 3 = 6 for element 2.

Try It Yourselfredirect icon

Table of Content

[Naive Approach] Using Nested Loops - O(n^2) Time O(n) Space

The idea is to traverse the array and, for every element that has not been processed before, count its frequency by scanning the entire array. Maintain a cumulative frequency and print the result for each distinct element.

C++ `

#include <bits/stdc++.h> using namespace std;

vector countFreq(vector &arr) {

int n = arr.size();

vector<int> res;

// To mark already processed elements
vector<bool> visited(n, false);

vector<pair<int, int>> freqs;

// Count frequency of every distinct element
for (int i = 0; i < n; i++)
{

    if (visited[i])
    {
        continue;
    }

    int freq = 0;

    for (int j = 0; j < n; j++)
    {

        if (arr[i] == arr[j])
        {
            freq++;

            if (j > i)
            {
                visited[j] = true;
            }
        }
    }

    freqs.push_back({arr[i], freq});
}

// Sort distinct elements
sort(freqs.begin(), freqs.end());

int cumul = 0;

// Generate cumulative frequencies
for (auto &p : freqs)
{
    cumul += p.second;
    res.push_back(cumul);
}

return res;

}

// Driver Code int main() {

vector<int> arr = {1, 2, 2, 1, 3, 4};

vector<int> res = countFreq(arr);

cout << "[";

for (int i = 0; i < res.size(); i++)
{

    cout << res[i];

    if (i != res.size() - 1)
    {
        cout << ", ";
    }
}

cout << "]";

return 0;

}

Java

import java.util.*;

public class GfG {

public static int[] countFreq(int[] arr)
{

    int n = arr.length;

    ArrayList<Integer> res = new ArrayList<>();

    // To mark already processed elements
    boolean[] visited = new boolean[n];

    ArrayList<int[]> freqs = new ArrayList<>();

    // Count frequency of every distinct element
    for (int i = 0; i < n; i++) {

        if (visited[i]) {
            continue;
        }

        int freq = 0;

        for (int j = 0; j < n; j++) {

            if (arr[i] == arr[j]) {
                freq++;

                if (j > i) {
                    visited[j] = true;
                }
            }
        }

        freqs.add(new int[] { arr[i], freq });
    }

    // Sort distinct elements
    freqs.sort((a, b) -> Integer.compare(a[0], b[0]));

    int cumul = 0;

    // Generate cumulative frequencies
    for (int[] p : freqs) {
        cumul += p[1];
        res.add(cumul);
    }

    int[] ans = new int[res.size()];

    for (int i = 0; i < res.size(); i++) {
        ans[i] = res.get(i);
    }

    return ans;
}

// Driver Code
public static void main(String[] args)
{

    int[] arr = { 1, 2, 2, 1, 3, 4 };

    int[] res = countFreq(arr);

    System.out.print("[");

    for (int i = 0; i < res.length; i++) {

        System.out.print(res[i]);

        if (i != res.length - 1) {
            System.out.print(", ");
        }
    }

    System.out.print("]");
}

}

Python

def countFreq(arr): n = len(arr) res = [] # To mark already processed elements visited = [False] * n freqs = [] # Count frequency of every distinct element for i in range(n): if visited[i]: continue freq = 0 for j in range(n): if arr[i] == arr[j]: freq += 1 if j > i: visited[j] = True freqs.append((arr[i], freq)) # Sort distinct elements freqs.sort(key=lambda x: x[0]) cumul = 0 # Generate cumulative frequencies for p in freqs: cumul += p[1] res.append(cumul) return res

Driver Code

if name == 'main': arr = [1, 2, 2, 1, 3, 4] res = countFreq(arr) print('[', end='') for i in range(len(res)): print(res[i], end='' if i == len(res) - 1 else ', ') print(']')

C#

using System; using System.Collections.Generic; using System.Linq;

class GfG { public static List countFreq(List arr) { int n = arr.Count; List res = new List(); // To mark already processed elements bool[] visited = new bool[n]; List<Tuple<int, int> > freqs = new List<Tuple<int, int> >(); // Count frequency of every distinct element for (int i = 0; i < n; i++) { if (visited[i]) { continue; } int freq = 0; for (int j = 0; j < n; j++) { if (arr[i] == arr[j]) { freq++; if (j > i) { visited[j] = true; } } } freqs.Add(new Tuple<int, int>(arr[i], freq)); } // Sort distinct elements freqs = freqs.OrderBy(x = > x.Item1).ToList(); int cumul = 0; // Generate cumulative frequencies foreach(var p in freqs) { cumul += p.Item2; res.Add(cumul); } return res; } // Driver Code public static void Main() { List arr = new List{ 1, 2, 2, 1, 3, 4 }; List res = countFreq(arr); Console.Write('['); for (int i = 0; i < res.Count; i++) { Console.Write(res[i]); if (i != res.Count - 1) { Console.Write(", "); } } Console.Write(']'); } }

JavaScript

function countFreq(arr) { let n = arr.length; let res = []; // To mark already processed elements let visited = new Array(n).fill(false); let freqs = []; // Count frequency of every distinct element for (let i = 0; i < n; i++) { if (visited[i]) { continue; } let freq = 0; for (let j = 0; j < n; j++) { if (arr[i] === arr[j]) { freq++; if (j > i) { visited[j] = true; } } } freqs.push([ arr[i], freq ]); } // Sort distinct elements freqs.sort((a, b) => a[0] - b[0]); let cumul = 0; // Generate cumulative frequencies for (let p of freqs) { cumul += p[1]; res.push(cumul); } return res; } // Driver Code let arr = [ 1, 2, 2, 1, 3, 4 ]; let res = countFreq(arr); console.log("[" + res.join(", ") + "]");

`

**Time Complexity: O(n^2)
**Auxiliary Space: O(n)

[Better Approach] Using Sorting - O(n log n) Time O(1) Space

The idea is to sort the array so that equal elements become adjacent. Then traverse the sorted array, compute frequencies of distinct elements, and keep adding them to obtain cumulative frequencies.

C++ `

#include <bits/stdc++.h> using namespace std;

vector countFreq(vector &arr) {

vector<int> res;

// Sort the array so equal elements become adjacent
sort(arr.begin(), arr.end());

int n = arr.size();
int cumul = 0;

// Count frequency of each distinct element
for (int i = 0; i < n;)
{

    int val = arr[i];
    int freq = 0;

    while (i < n && arr[i] == val)
    {
        freq++;
        i++;
    }

    // Update cumulative frequency
    cumul += freq;
    res.push_back(cumul);
}

return res;

}

// Driver Code int main() {

vector<int> arr = {1, 2, 2, 1, 3, 4};

vector<int> res = countFreq(arr);

cout << "[";

for (int i = 0; i < res.size(); i++)
{

    cout << res[i];

    if (i != res.size() - 1)
    {
        cout << ", ";
    }
}

cout << "]";

return 0;

}

Java

import java.util.ArrayList; import java.util.Arrays;

public class GfG { public static int[] countFreq(int[] arr) { ArrayList res = new ArrayList<>();

    // Sort the array so equal elements become adjacent
    Arrays.sort(arr);

    int n = arr.length;
    int cumul = 0;

    // Count frequency of each distinct element
    for (int i = 0; i < n;) {
        int val = arr[i];
        int freq = 0;

        while (i < n && arr[i] == val) {
            freq++;
            i++;
        }

        // Update cumulative frequency
        cumul += freq;
        res.add(cumul);
    }

    int[] ans = new int[res.size()];

    for (int i = 0; i < res.size(); i++) {
        ans[i] = res.get(i);
    }

    return ans;
}

// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 2, 2, 1, 3, 4 };

    int[] res = countFreq(arr);

    System.out.print("[");

    for (int i = 0; i < res.length; i++) {
        System.out.print(res[i]);

        if (i != res.length - 1) {
            System.out.print(", ");
        }
    }

    System.out.print("]");
}

}

Python

def countFreq(arr): res = []

# Sort the array so equal elements become adjacent
arr.sort()

n = len(arr)
cumul = 0

# Count frequency of each distinct element
i = 0
while i < n:
    val = arr[i]
    freq = 0

    while i < n and arr[i] == val:
        freq += 1
        i += 1

    # Update cumulative frequency
    cumul += freq
    res.append(cumul)

return res

Driver Code

if name == 'main': arr = [1, 2, 2, 1, 3, 4] res = countFreq(arr) print('[', end='') for i in range(len(res)): print(res[i], end='' if i == len(res) - 1 else ', ') print(']')

C#

using System; using System.Collections.Generic;

public class GfG { public static List countFreq(int[] arr) { List res = new List();

    // Sort the array so equal elements become adjacent
    Array.Sort(arr);

    int n = arr.Length;
    int cumul = 0;

    // Count frequency of each distinct element
    for (int i = 0; i < n;) {
        int val = arr[i];
        int freq = 0;

        while (i < n && arr[i] == val) {
            freq++;
            i++;
        }

        // Update cumulative frequency
        cumul += freq;
        res.Add(cumul);
    }

    return res;
}

public static void Main()
{
    int[] arr = { 1, 2, 2, 1, 3, 4 };
    List<int> res = countFreq(arr);

    Console.Write("[");

    for (int i = 0; i < res.Count; i++) {
        Console.Write(res[i]);
        if (i != res.Count - 1) {
            Console.Write(", ");
        }
    }

    Console.Write("]");
}

}

JavaScript

function countFreq(arr) { let res = [];

// Sort the array so equal elements become adjacent
arr.sort((a, b) => a - b);

let n = arr.length;
let cumul = 0;

// Count frequency of each distinct element
let i = 0;
while (i < n) {
    let val = arr[i];
    let freq = 0;

    while (i < n && arr[i] === val) {
        freq++;
        i++;
    }

    // Update cumulative frequency
    cumul += freq;
    res.push(cumul);
}

return res;

}

// Driver Code let arr = [ 1, 2, 2, 1, 3, 4 ]; let res = countFreq(arr);

console.log("["); for (let i = 0; i < res.length; i++) { process.stdout.write(res[i].toString()); if (i !== res.length - 1) { process.stdout.write(", "); } } console.log("]");

`

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

[Expected Approach] Using Hashing and Set - O(n + k log k) Time O(n) Space

The idea is to first store the frequency of every element in a hash map. Then insert each distinct element along with its frequency into an ordered set, which keeps the elements sorted by value. Finally, traverse the set and generate cumulative frequencies.

C++ `

#include <bits/stdc++.h> using namespace std;

vector countFreq(vector &arr) { // Insert elements and their // frequencies in hash map. int n = arr.size(); unordered_map<int, int> hm; for (int i = 0; i < n; i++) hm[arr[i]]++;

// Declare a set
set<pair<int, int>> st;

// insert the element and
// and insert its frequency in a set
for (auto x : hm)
{
    st.insert({x.first, x.second});
}

int cumul = 0;

// iterate the set and print the
// cumulative frequency
vector<int> v;

for (auto x : st)
{
    cumul += x.second;
    v.push_back(cumul);
}
return v;

}

// Driver Code int main() {

vector<int> arr = {1, 2, 2, 1, 3, 4};

vector<int> res = countFreq(arr);

cout << "[";

for (int i = 0; i < res.size(); i++)
{

    cout << res[i];

    if (i != res.size() - 1)
    {
        cout << ", ";
    }
}

cout << "]";

return 0;

}

Java

import java.util.*;

public class GfG { public static int[] countFreq(int[] arr) { // Insert elements and their // frequencies in hash map. int n = arr.length; HashMap<Integer, Integer> hm = new HashMap<>();

    for (int i = 0; i < n; i++)
        hm.put(arr[i], hm.getOrDefault(arr[i], 0) + 1);

    // Declare a set
    Set<Map.Entry<Integer, Integer> > st
        = new TreeSet<>(Map.Entry.comparingByKey());

    // insert the element and
    // and insert its frequency in a set
    st.addAll(hm.entrySet());

    int cumul = 0;

    // iterate the set and generate the
    // cumulative frequency
    int[] res = new int[st.size()];
    int idx = 0;

    for (Map.Entry<Integer, Integer> x : st) {
        cumul += x.getValue();
        res[idx++] = cumul;
    }

    return res;
}

// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 2, 2, 1, 3, 4 };

    int[] res = countFreq(arr);

    System.out.print("[");

    for (int i = 0; i < res.length; i++) {

        System.out.print(res[i]);

        if (i != res.length - 1) {
            System.out.print(", ");
        }
    }

    System.out.print("]");
}

}

Python

from collections import OrderedDict

def countFreq(arr): # Insert elements and their # frequencies in hash map. n = len(arr) hm = {} for i in range(n): if arr[i] in hm: hm[arr[i]] += 1 else: hm[arr[i]] = 1

# Declare a set
st = OrderedDict(sorted(hm.items()))

# insert the element and
# and insert its frequency in a set
st = OrderedDict(sorted(hm.items()))

cumul = 0

# iterate the set and print the
# cumulative frequency
v = []

for key, value in st.items():
    cumul += value
    v.append(cumul)
return v

Driver Code

if name == 'main': arr = [1, 2, 2, 1, 3, 4] res = countFreq(arr) print('[', end='') for i in range(len(res)): print(res[i], end='' if i == len(res) - 1 else ', ') print(']')

C#

using System; using System.Collections.Generic; using System.Linq;

public class GfG { public static List countFreq(int[] arr) { // Insert elements and their // frequencies in hash map. int n = arr.Length; Dictionary<int, int> hm = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { if (hm.ContainsKey(arr[i])) hm[arr[i]]++; else hm[arr[i]] = 1; }

    // Declare a set
    var st = hm.OrderBy(x = > x.Key);

    int cumul = 0;

    // iterate the set and print the
    // cumulative frequency
    List<int> v = new List<int>();

    foreach(var x in st)
    {
        cumul += x.Value;
        v.Add(cumul);
    }
    return v;
}

// Driver Code
public static void Main()
{
    int[] arr = { 1, 2, 2, 1, 3, 4 };

    List<int> res = countFreq(arr);

    Console.Write("[");

    for (int i = 0; i < res.Count; i++) {
        Console.Write(res[i]);

        if (i != res.Count - 1) {
            Console.Write(", ");
        }
    }

    Console.Write("]");
}

}

JavaScript

function countFreq(arr) {

// Insert elements and their
// frequencies in hash map.
let n = arr.length;
let hm = new Map();
for (let i = 0; i < n; i++)
    hm.set(arr[i], (hm.get(arr[i]) || 0) + 1);

// Declare a set
let st = new Set();

// insert the element and
// and insert its frequency in a set
for (let [key, value] of hm) {
    st.add([key, value]);
}

let cumul = 0;

// iterate the set and print the
// cumulative frequency
let v = [];

let stArray = Array.from(st);
stArray.sort((a, b) => a[0] - b[0]);

for (let x of stArray) {
    cumul += x[1];
    v.push(cumul);
}
return v;

}

// Driver Code let arr = [1, 2, 2, 1, 3, 4];

let res = countFreq(arr);

console.log('[');

for (let i = 0; i < res.length; i++) { console.log(res[i]); if (i!= res.length - 1) { console.log(', '); } }

console.log(']');

`

**Time Complexity: O(n + k log k)
**Auxiliary Space: O(n)