Tasks Details
easy
1.
Distinct
Compute number of distinct values in an array.
Task Score
100%
Correctness
100%
Performance
100%
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] = 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 C#
Time spent on task 12 minutes
Notes
not defined yet
Code: 09:45:14 UTC,
cs,
verify,
result: Failed
using System;
using System.Collections.Generic;
class Solution {
public int solution(int[] A) {
List<int> li = new List<int>();
for(int i = 0; i < A.Length; i++)
{
bool isFound = false;
for(int j = 0; j < li.Count; j++)
{
if(A[i] == li[j])
{
found = true;
break;
}
}
if(!found) li.Add(A[i]);
}
return li.Count;
}
}
Analysis
Compile error
Compilation failed: 2 error(s), 0 warnings Solution.cs(17,21): error CS0103: The name `found' does not exist in the current context Solution.cs(22,17): error CS0103: The name `found' does not exist in the current context
Code: 09:46:32 UTC,
cs,
verify,
result: Passed
using System;
using System.Collections.Generic;
class Solution {
public int solution(int[] A) {
List<int> li = new List<int>();
for(int i = 0; i < A.Length; i++)
{
bool found = false;
for(int j = 0; j < li.Count; j++)
{
if(A[i] == li[j])
{
found = true;
break;
}
}
if(!found) li.Add(A[i]);
}
return li.Count;
}
}
Analysis
Analysis
Compile error
Compilation failed: 1 error(s), 0 warnings Solution.cs(7,25): error CS1061: Type `int[]' does not contain a definition for `Distinct' and no extension method `Distinct' of type `int[]' could be found. Are you missing `System.Linq' using directive? /opt/lang/mono/lib/mono/4.5/mscorlib.dll (Location of the symbol related to previous error)
Analysis
Analysis
Analysis
Compile error
Compilation failed: 1 error(s), 0 warnings Solution.cs(7,8): error CS1525: Unexpected symbol `else'
Analysis
Analysis
Analysis summary
The solution obtained perfect score.
Analysis
Detected time complexity:
O(N*log(N)) or O(N)
expand all
Correctness tests
1.
0.061 s
OK
1.
0.062 s
OK
2.
0.065 s
OK
1.
0.065 s
OK
1.
0.062 s
OK
1.
0.062 s
OK
1.
0.062 s
OK
1.
0.066 s
OK
1.
0.064 s
OK
1.
0.066 s
OK