Learner Level

Implement the countDistinctValues method that counts how many different values are present in the array.

The input contains an integer array nums and its length size. Your task is to count how many distinct values are present in the array.

Distinct means each different value is counted only once, even if it appears multiple times. For example, [1,2,2,3,1] contains three distinct values: 1, 2, and 3.

Example 1

Input
nums (int[]) = [1,2,2,3,1]
size (int) = 5
Returns (int) 3

Example 2

Input
nums (int[]) = [4,4,4]
size (int) = 3
Returns (int) 1

Example 3

Input
nums (int[]) = [-1,0,-1,2]
size (int) = 4
Returns (int) 3

Use a set because a set stores each value only once.

Insert every array value into the set. After all values are processed, the size of the set is the number of distinct values.

Pseudocode:

function countDistinctValues(nums, size):
    seen = empty set
    for each value in nums:
        add value to seen
    return size of seen
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.