Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Frequency of Distinct Elements

Print a count for each distinct integer in sorted order with Python. Students combine a frequency dictionary, a set of keys, and numeric ordering for display.

AdvancedPhase 4 - Level 5: Logical & AppliedExample 9 of 14
frequency-of-distinct-elements.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Frequency of distinct elements
8freq = {}
9for element in arr:
10 freq[element] = freq.get(element, 0) + 1
11
12# Display
13print("Frequency of distinct elements:")
14for element in sorted(set(arr)):
15 print(f"{element}: {freq[element]}")

Output

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

In this one

  • Separate distinct display from counts
  • Preserve full frequencies
  • Order numeric keys

How it works

  1. 1

    Build the frequency dictionary.

  2. 2

    Visit sorted distinct input values.

  3. 3

    Print each key with its stored full count.

Edge cases

Why use a set for display?

Why use a set for display?

Each distinct integer should appear on one row.

Does sorting the set change arr?

Does sorting the set change arr?

No. arr remains in its input order.

What's going on

The counting pass updates freq using get with a zero default. The display pass visits sorted(set(arr)).

The set prevents repeated output rows; sorting gives a predictable ascending value order. freq[element] supplies the full occurrence count, so duplicates are not lost from the statistics. Empty input has no value rows after the heading.

Why use a set for display? Each distinct integer should appear on one row.

Does sorting the set change arr? No. arr remains in its input order.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Where are occurrence counts stored?

Pick an answer to check it.

Question 2

Why use a set for display?

Pick an answer to check it.

Questions people ask

Why use a set for display?

Each distinct integer should appear on one row.

Does sorting the set change arr?

No. arr remains in its input order.

Where are occurrence counts stored?

In freq.