Tutorialspoint
Problem
Solution
Submissions

Frequency of Each Element in an array.

Certification: Basic Level Accuracy: 100% Submissions: 7 Points: 5

Write a C++ program that counts the frequency of each element in a given array.

Example 1
  • Input: array = [1, 2, 3, 2, 1, 3, 4, 5]
  • Output: 1 : 2 2 : 2 3 : 2 4 : 1 5 : 1
  • Explanation:
    • Step 1: Create a data structure to store element frequencies.
    • Step 2: Traverse the array and count occurrences of each element.
    • Step 3: Print each unique element and its frequency.
Example 2
  • Input: array = [10, 20, 10, 30, 20, 20]
  • Output: 10 : 2 20 : 3 30 : 1
  • Explanation:
    • Step 1: Create a data structure to store element frequencies.
    • Step 2: Traverse the array and count occurrences of each element.
    • Step 3: Print each unique element and its frequency.
Constraints
  • 1 ≤ len(array) ≤ 10^6
  • -10^9 ≤ array[i] ≤ 10^9
  • Time Complexity: O(n), where n is the length of the array
  • Space Complexity: O(n)
Hash MapControl StructuresCognizantDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a hash map (or dictionary) to store the frequency of each element.
  • Iterate through the array and update the frequency count in the hash map.
  • Print the elements along with their frequencies.

Steps to solve by this approach:

 Step 1: Define a function countFrequency that takes a constant vector of integers.
 Step 2: Create an unordered_map to store element frequencies.
 Step 3: Iterate through the input array and increment the frequency for each element.
 Step 4: Iterate through the frequency map and print each element with its frequency.
 Step 5: In main, create a vector with values and call countFrequency.

Submitted Code :