PermCheck – Codility – Solution

Java solution to Codility PermCheck (Permuation Check) problem (Lesson 4 – Counting Elements) which scored 100%. The problem is to check if the given array is a permutation. The main strategy is to use two java.util.HashSets: 1) a perfect set and 2) the actual set and check for the missing element in the actual set that exists in the perfect set.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.codility.lesson04.countingelements;

import java.util.HashSet;
import java.util.Set;

public class PermutationCheck {
  public int solution(int[] A) {
    Set testedSet = new HashSet();
    Set perfectSet = new HashSet();
   
    for(int i=0; i<A.length; i++) {
      testedSet.add(A[i]);
      perfectSet.add(i+1);
    }
   
    for(int current : perfectSet) {
      //as soon as find 1 element missing return false
      if(!testedSet.contains(current)) return 0;
    }
    return 1;
  }
}

TestNG test cases for this problem which all passed:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package test.com.codility.lesson04.countingelements;
import org.testng.Assert;
import org.testng.annotations.*;

import com.codility.lesson04.countingelements.PermutationCheck;

public class PermutationCheckTests {
  private PermutationCheck solution;
 
  @BeforeTest
  public void setUp() {
    solution = new PermutationCheck();
  }

  @DataProvider(name = "test1")
  public Object [][] createData1() {
    return new Object [][] {
      new Object [] { new int [] {                1 }, 1 },
      new Object [] { new int [] {                2 }, 0 },
      new Object [] { new int [] {             1, 2 }, 1 },
      new Object [] { new int [] {             2, 2 }, 0 },
      new Object [] { new int [] {          1, 3, 2 }, 1 },
      new Object [] { new int [] {          1, 3, 3 }, 0 },
      new Object [] { new int [] {       4, 1, 3, 2 }, 1 },
      new Object [] { new int [] {          4, 1, 3 }, 0 },
      new Object [] { new int [] {    1, 3, 5, 4, 2 }, 1 },
      new Object [] { new int [] { 1, 3, 6, 4, 1, 2 }, 0 },
      new Object [] { new int [] { 1, 3, 5, 4, 6, 2 }, 1 },
      new Object [] { new int [] {          1000000 }, 0 },
      new Object [] { new int [] {       1, 1000000 }, 0 },
    };
  }

  @Test(dataProvider = "test1")
  public void verifySolution(int [] pA, int pExpected) {
    Assert.assertEquals(solution.solution(pA), pExpected);
  }
}