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
50%
Correctness
66%
Performance
0%

Task description

Write a function

function solution(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 JavaScript
Time spent on task 6 minutes
Notes
not defined yet
Task timeline
21:28:06
21:34:00

Away from Codility tab

0%

Code: 21:34:00 UTC, js, final, score:  50
// you can use console.log for debugging purposes, i.e.
// console.log('this is a debug message');

function solution(A) {
    A.sort(function(a,b){return a > b});
    var count = 1;
    
    if(A.length == 0) return 0;
    
    for(var i=0; i<A.length-1;i++){
        if(A[i] !== A[i+1]){
            count++;
        }
    }
    
    return count;
}
Analysis summary

The following issues have been detected: wrong answers.

Analysis
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
WRONG ANSWER
got 99 expected 96
medium2
chaotic sequence of value sfrom [0..1K], length=200
WRONG ANSWER
got 198 expected 179
medium3
chaotic sequence of values from [0..10], length=200
WRONG ANSWER
got 83 expected 11
expand all Performance tests
large1
chaotic sequence of values from [0..100K], length=10K
WRONG ANSWER
got 9997 expected 9522
large_random1
chaotic sequence of values from [-1M..1M], length=100K
WRONG ANSWER
got 100000 expected 97534
large_random2
another chaotic sequence of values from [-1M..1M], length=100K
WRONG ANSWER
got 99997 expected 97527