Finding the Frequency of Elements in an Array

Understanding Frequency Calculation

Finding the frequency of elements in an array involves counting the number of times each element appears.

We will explore three different methods to determine the frequency using Python.

Method 1: Using a Loop

This method iterates through the array and counts occurrences of each element.

def find_frequency(arr):
    visited = [False] * len(arr)
    
    for i in range(len(arr)):
        if visited[i]:
            continue
        count = 1
        for j in range(i + 1, len(arr)):
            if arr[i] == arr[j]:
                count += 1
                visited[j] = True
        print(f"{arr[i]} appears {count} times.")

arr = [1, 2, 3, 2, 1, 3, 3]
find_frequency(arr)
            
Output:
1 appears 2 times.
2 appears 2 times.
3 appears 3 times.

Method 2: Using a Dictionary

This method utilizes a dictionary to store frequencies.

def find_frequency(arr):
    freq_map = {}
    
    for num in arr:
        freq_map[num] = freq_map.get(num, 0) + 1
    
    for key, value in freq_map.items():
        print(f"{key} appears {value} times.")

arr = [1, 2, 3, 2, 1, 3, 3]
find_frequency(arr)
            
Output:
1 appears 2 times.
2 appears 2 times.
3 appears 3 times.

Method 3: Using Sorting

This method sorts the array first and then counts occurrences.

def find_frequency(arr):
    arr.sort()
    i = 0
    while i < len(arr):
        count = 1
        while i < len(arr) - 1 and arr[i] == arr[i + 1]:
            count += 1
            i += 1
        print(f"{arr[i]} appears {count} times.")
        i += 1

arr = [1, 2, 3, 2, 1, 3, 3]
find_frequency(arr)
            
Output:
1 appears 2 times.
2 appears 2 times.
3 appears 3 times.
Top 100 Codes By Learn-for-free
Start Preparing Arraysform here👇

Below You will find some of the most important codes in languages like C, C++, Java, and Python. These codes are of prime importance for college semester exams and online tests.

Getting Started

Find Largest Element in an Array: C C++ Java Python

Find Smallest Element in an Array: C C++ Java Python

Find the Smallest and Largest Element in an Array: C C++ Java Python

Find Second Smallest Element in an Array: C C++ Java Python

Calculate the Sum of Elements in an Array: C C++ Java Python

Reverse an Array: C C++ Java Python

Sort First Half in Ascending Order and Second Half in Descending: C C++ Java Python

Finding the Frequency of Elements in an Array: C C++ Java Python

Counting the Number of Even and Odd Elements in an Array: C C++ Java Python

Finding Maximum Product Sub-array in a Given Array: C C++ Java Python

Finding Arrays are Disjoint or Not: C C++ Java Python

Finding Equilibrium Index of an Array: C C++ Java Python

Rotation of Elements of Array - Left and Right: C C++ Java Python

Balanced Parenthesis Problem: C C++ Java Python