Frequency of Distinct Elements

Find frequency of each distinct element.

Logic BuildingAdvanced
Logic Building
# Take array
n = int(input("Enter array size: "))
arr = []
for i in range(n):
    arr.append(int(input(f"Element {i+1}: ")))

# Frequency of distinct elements
freq = {}
for element in arr:
    freq[element] = freq.get(element, 0) + 1

# Display
print("Frequency of distinct elements:")
for element in sorted(set(arr)):
    print(f"{element}: {freq[element]}")

Output

Enter array size: 6
Element 1: 1
Element 2: 2
Element 2: 2
Element 3: 3
Element 4: 2
Element 5: 1
Frequency of distinct elements:
1: 2
2: 3
3: 1

Count frequency using dictionary.

Key Concepts:

  • Use dictionary to count
  • Get distinct elements using set
  • Display frequency for each