Thursday 18 June 2015

CODILITY.COM - LESSON 2 - PERMCHECK

(Codility.com is a tool to test coding skills on behalf of companies advertising roles. They also have a training centre with interesting topics and practical tests that you can do in order to improve your skills. You can use different languages in their IDE.)

PROBLEM BY CODILITY.COM
A non-empty zero-indexed array A consisting of N integers is given.
permutation is a sequence containing each element from 1 to N once, and only once.
For example, array A such that:
    A[0] = 4
    A[1] = 1
    A[2] = 3
    A[3] = 2
is a permutation, but array A such that:
    A[0] = 4
    A[1] = 1
    A[2] = 3
is not a permutation, because value 2 is missing.
The goal is to check whether array A is a permutation.
Write a function that, given a zero-indexed array A, returns 1 if array A is a permutation and 0 if it is not.
Assume that:
  • N is an integer within the range [1..100,000];
  • each element of array A is an integer within the range [1..1,000,000,000].
MY SOLUTION (100% score, time complexity O(n) or O(N*log(n)) )

class Solution {
    public int solution(int[] A) {
        int l = A.Length;       
        int [] B = A.Distinct().ToArray();
        Array.Sort(B);
        int lB = B.Length;
        
        if ( l <=0) return 0;
        if (l == 1 && A[0] == 1) return 1;
        
        return (B[lB-1] == lB && lB == l)? 1 : 0;
    }
}

Copy the original array into a new array but eliminating any possible integers that are repeated (arrayName.Distinct().ToArray()
And then sort them out so the they are ordered. (Array.Sort(arrayName). This allows to check that the last value of the array is = to the index - 1. 
Check if both array lengths (original and sorted) are the same.  
It the last two points are true, then it is a permutation.
This stands for lengths greater than 1. For arrays of 1 or zero elements, there are special controls.
If the length is zero it should return zero.
If the length is 1 and the first element is 1 then it should return 1 as it is a permutation.

PR

No comments:

Post a Comment