Your browser is not supported. Please, update your browser or switch to a different one. Learn more about what browsers are supported.

Check out Codility training tasks
Tasks Details
easy
Compute number of distinct values in an array.
Task Score
100%
Correctness
100%
Performance
100%

Task description

Write a function

class Solution { public int solution(int[] A); }

that, given an array A consisting of N integers, returns the number of distinct values in array A.

For example, given array A consisting of six elements such that:

A[0] = 2 A[1] = 1 A[2] = 1 A[3] = 2 A[4] = 3 A[5] = 1

the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [0..100,000];
  • each element of array A is an integer within the range [−1,000,000..1,000,000].
Copyright 2009–2025 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Solution
Programming language used C#
Time spent on task 4 minutes
Notes
not defined yet
Task timeline
04:25:05
04:28:20

Away from Codility tab

0%

Code: 04:28:20 UTC, cs, final, score:  100
using System;
// you can also use other imports, for example:
// using System.Collections.Generic;

// you can use Console.WriteLine for debugging purposes, e.g.
// Console.WriteLine("this is a debug message");

class Solution {
    public int solution(int[] A) {
        // write your code in C# 6.0 with .NET 4.5 (Mono)
        if (A.Length == 0) return 0;

        var distinct = 1;

        Array.Sort(A);

        for (var i = 1; i < A.Length; i++)
        {
            distinct += (A[i - 1] != A[i]) ? 1 : 0;
        }

        return distinct;
    }
}
Analysis summary

The solution obtained perfect score.

Analysis
Detected time complexity:
O(N) or O(N*log(N))
expand all Example tests
example1
example test, positive answer
OK
expand all Correctness tests
extreme_empty
empty sequence
OK
extreme_single
sequence of one element
OK
extreme_two_elems
sequence of three distinct elements
OK
extreme_one_value
sequence of 10 equal elements
OK
extreme_negative
sequence of negative elements, length=5
OK
extreme_big_values
sequence with big values, length=5
OK
medium1
chaotic sequence of value sfrom [0..1K], length=100
OK
medium2
chaotic sequence of value sfrom [0..1K], length=200
OK
medium3
chaotic sequence of values from [0..10], length=200
OK
expand all Performance tests
large1
chaotic sequence of values from [0..100K], length=10K
OK
large_random1
chaotic sequence of values from [-1M..1M], length=100K
OK
large_random2
another chaotic sequence of values from [-1M..1M], length=100K
OK