Tasks Details
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] = 1the 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
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
expand all
Correctness tests
expand all
Performance tests
large_random1
chaotic sequence of values from [-1M..1M], length=100K
chaotic sequence of values from [-1M..1M], length=100K
WRONG ANSWER
got 100000 expected 97534
got 100000 expected 97534
large_random2
another chaotic sequence of values from [-1M..1M], length=100K
another chaotic sequence of values from [-1M..1M], length=100K
WRONG ANSWER
got 99997 expected 97527
got 99997 expected 97527