702684. Cumulative frequency of count of each element in an unsorted array

Easy

Frequency of Each Element in an Unsorted Array

Summary

Given an unsorted array, find the cumulative frequency of each element. The cumulative frequency for a particular element is the count of that element up to that point in the array.

This problem involves arrays and hash tables, requiring the use of these concepts to solve it efficiently.

Detailed Explanation

To solve this problem, we'll iterate through the array once, storing the counts of each element in a hash table. Then, for each element, we'll calculate its cumulative frequency by summing up the counts from the start of the array to that point.

Here's the step-by-step breakdown:

  1. Initialize an empty hash table (e.g., HashMap in Java or Python dictionaries) to store the counts of each element.
  2. Iterate through the array, and for each element:
    • Look up its count in the hash table. If it's not present, set its count to 1; otherwise, increment its current count by 1.
  3. For each element, calculate its cumulative frequency by summing up the counts from the start of the array to that point.
  4. Return the cumulative frequencies for all elements.

Time complexity: O(n), where n is the size of the input array. We only need to iterate through the array once and perform constant-time operations (hash table lookups and updates) for each element.

Space complexity: O(min(n, m)), where m is the number of unique elements in the array. We store at most one count per unique element in the hash table.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.HashMap;
import java.util.Map;

public class CumulativeFrequency {
    public static Map<Integer, Integer> cumulativeFrequency(int[] arr) {
        Map<Integer, Integer> counts = new HashMap<>();
        for (int num : arr) {
            counts.put(num, counts.getOrDefault(num, 0) + 1);
        }
        int cumulativeFrequency = 0;
        for (int i = 0; i < arr.length; i++) {
            cumulativeFrequency += counts.get(arr[i]);
            counts.put(arr[i], cumulativeFrequency);
        }
        return counts;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.