AlgoInsight

DSA problem

Frequency of Each Element in an Array

EasyArraysPattern: Hash MapbeginnerFree

Given an array of N integers, compute the frequency (count of occurrences) of each distinct element.

This is your introduction to hash maps in practice. Iterate through the array, and for each element increment its count in a hash map (dictionary / HashMap / object). Without a hash map you would need nested loops for O(N^2); with one it is O(N).

Counting occurrences is a pattern you will use constantly - grouping items, building indexes, detecting duplicates, and more. Hash maps are the most frequently used data structure in real-world programming and interviews.

Examples

Example 1
Input: nums = [1, 3, 2, 1, 4, 2, 1, 3]
Output: {1: 3, 3: 2, 2: 2, 4: 1}
Explanation: 1 appears 3 times, 3 appears twice, 2 appears twice, and 4 appears once.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

array

Browse all DSA problems