My experience on my daily works... helping others ease each other

Monday, January 13, 2020

Codility - PermCheck (Check whether array A is a permutation)


This is the second lesson in Codility. Given an array of integer N, you need to find if the given array is a permutation array or perfect array in sequence (if all numbers are sorted accordingly). The full explanation of the lesson is here.

It does not take me long compared to the previous lesson. I scored 100% on the first trial and here is the explanation of my code.

Since it already stated that the array starts from a positive number, I just set the expected int is 1 and missing to 0
int expectedInt = 1;
int missingInt = 0;
Then, the array is sorted accordingly. I’m using java.util.Arrays library
 Arrays.sort(A);
To find the missing int, just loop the sorted array and find the first occurrence of the missing int.
for (int x : A){ //loop to find the missing int
     if (x == expectedInt){
          expectedInt++;
     } else {
         missingInt = expectedInt;
     }
 }

This code is not perfected yet as it will continue to search despite it found the missing int. I should further improve it later. However, for codility purposes, it stops here. You can further enhance the code by implementing the break clause once found the first missing int.
The code
And here is the result. Ya, it shows 2 minutes; that is because I test it again to snapshot the result :). In actual, for a few trials, it took me around 2 hours to perfect it and scored 100%
Result

You can download the full code at
  1. Bitbucket — git clone https://masteramuk@bitbucket.org/fullstacksdev/codility-permcheck.git
  2. Github — git clone https://github.com/masteramuk/codility-lessoncode.git





Share:

0 comments:

About Me

Somewhere, Selangor, Malaysia
An IT by profession, a beginner in photography

Blog Archive

Blogger templates