Python BasicsEasy

Counting Distinct Elements in an Array

Detailed guide and Python implementation for the 'Counting Distinct Elements in an Array' problem.

Problem Statement

Easy

Write a function count_distinct(arr) that takes a list of integers arr and returns the count of distinct (unique) elements in the array.

Constraints
  • 0 <= len(arr) <= 10^5
  • -10^6 <= arr[i] <= 10^6

Examples

Example 1
Input
arr = [1, 2, 2, 3, 3, 3]
Output
3
Explanation

The distinct elements are 1, 2, and 3. Count = 3.

Example 2
Input
arr = [5, 5, 5, 5]
Output
1
Explanation

Only one distinct element: 5.

Example 3
Input
arr = [1, 2, 3, 4, 5]
Output
5
Explanation

All elements are distinct.

Need a Hint?
Consider using Arrays-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.