Codility ‘Distinct’ Solution

Short Problem Definition:

Compute number of distinct values in an array.




expected worst-case time complexity is O(N * log(N));

expected worst-case space complexity is O(N)


Sorting in both C++ and Python takes N log N time. We know that for this particular problem sorting the array will be the dominant runtime complexity. This is the case for the second python solution. What about the other ones?

The first solution is a neat pythonic way of solving a distinct entries problem. The set is implemented as a hash table so it is possible that it will degrade to a linked list. Therefore the actual worst case would be N^2.

This is not the case with C++ (as code 3 shows). The std set is a Red-Black Tree and therefore has insertion complexity of log N. (overall N log N)

def solution(A):
    return len(set(A))

def solution(A):
    if len(A) == 0:
        return 0


    nr_values = 1
    last_value = A[0]

    for idx in xrange(1, len(A)):
        if A[idx] != last_value:
            nr_values += 1
            last_value = A[idx]

    return nr_values

#include <set>
int solution(const vector<int> &A) {
    std::set<int> theSet;

    for(int idx = 0; idx < A.size(); idx++){

    return theSet.size();

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

  • salmAn

    Java 8:

    Integer [] ints =[]::new);
    return (int) Arrays.asList(ints).stream().distinct().count();

  • Siavash Goudarzi


    function solution($A) {
    return count(array_unique($A));

  • Tanuj Sharma

    Java8 100%/100%

    import java.util.*;

    class Solution {
    public int solution(int[] A) {
    int count = 1;
    if(A.length == 0) return 0;
    for(int i=0 ; i < A.length-1 ; i++){
    return count;

  • Thomas

    C# code

    public static int solution(int[] a)
    int i;
    int k=1;
    for (i=0; i<=a.Length-2;i++)
    if (a[i] != a[i + 1])
    k = k + 1;

    return k;