();
8 | for (int i = 0; i < S.length(); i++) {
9 | char ch = S.charAt(i);
10 | if (ch == ')' || ch == ']' || ch == '}') {
11 | if (leftBrackets.empty()) {
12 | return 0;
13 | }
14 | char top = leftBrackets.pop();
15 | if ((ch == ')' && top != '(') || (ch == ']' && top != '[') || (ch == '}' && top != '{')) {
16 | return 0;
17 | }
18 | } else {
19 | leftBrackets.push(ch);
20 | }
21 | }
22 | return leftBrackets.empty() ? 1 : 0;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/codility/lessons/BinaryGap/BinaryGap.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.BinaryGap;
2 |
3 | /**
4 | * {@link #Bitwise Operation https://en.wikipedia.org/wiki/Bitwise_operation}
5 | *
6 | */
7 |
8 | public class BinaryGap {
9 | public int solution(int n) {
10 | // get rid of right-hand zeros
11 | while (n != 0 && (n & 1) == 0) {
12 | n >>>= 1;
13 | }
14 | System.out.println("n--->"+n);
15 |
16 | int max = 0;
17 | int gap = 0;
18 | while (n != 0) {
19 | if ((n & 1) == 0) {
20 | gap++;
21 | max = Math.max(gap, max);
22 | } else {
23 | gap = 0;
24 | }
25 | n >>>= 1;
26 | }
27 | return max;
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/codility/lessons/BinaryGap/BinaryGap2.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.BinaryGap;
2 |
3 | public class BinaryGap2 {
4 | public int solution(int N) {
5 | int pre = -1;
6 | int len = 0;
7 |
8 | while (N > 0) {
9 | int k = N & -N;
10 |
11 | int curr = (int) Math.log(k);
12 |
13 | N = N & (N - 1);
14 |
15 | if (pre != -1 && Math.abs(curr - pre) > len) {
16 | len = Math.abs(curr - pre) + 1;
17 | }
18 | pre = curr;
19 | }
20 |
21 | return len;
22 |
23 | }
24 |
25 | public static void main(String[] args) {
26 | BinaryGap2 gap =new BinaryGap2 ();
27 |
28 | int n = 9;
29 | int res = gap.solution(n);
30 | System.out.println("res--->"+res);
31 |
32 | res = gap.solution(529);
33 | System.out.println("res--->"+res);
34 |
35 | res = gap.solution(20);
36 | System.out.println("res--->"+res);
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/codility/lessons/BinaryGap/BinaryGap3.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.BinaryGap;
2 |
3 | public class BinaryGap3 {
4 | public int solution(int N) {
5 | int pre = -1;
6 | int len = 0;
7 |
8 | while (N > 0) {
9 | int k = N & -N;
10 |
11 | int curr = (int) Math.log(k);
12 |
13 | N = N & (N - 1);
14 |
15 | if (pre != -1 && Math.abs(curr - pre) > len) {
16 | len = Math.abs(curr - pre) + 1;
17 | }
18 | pre = curr;
19 | }
20 |
21 | return len;
22 |
23 | }
24 |
25 | public static void main(String[] args) {
26 | BinaryGap3 gap =new BinaryGap3 ();
27 |
28 | int n = 9;
29 | int res = gap.solution(n);
30 | System.out.println("res--->"+res);
31 |
32 | res = gap.solution(529);
33 | System.out.println("res--->"+res);
34 |
35 | res = gap.solution(20);
36 | System.out.println("res--->"+res);
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/codility/lessons/StacksQueues/Nesting.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.StacksQueues;
2 |
3 | public class Nesting {
4 |
5 | public int solution1(String S) {
6 | int N = S.length();
7 | // if the length of string s is odd, then it can't be nested.
8 | if (N % 2 == 1)
9 | return 0;
10 | char[] stack = new char[N];
11 | int num = 0;
12 | for (int i = 0; i < N; i++) {
13 | // push the '(' into the stack
14 | if (S.charAt(i) == '(')
15 | stack[num++] = S.charAt(i);
16 | // if the stack is not empty, pop the top element out.
17 | else if (num != 0)
18 | num--;
19 | // other situation means it's not a nested string
20 | else
21 | return 0;
22 | }
23 | if (num == 0)
24 | return 1;
25 | else
26 | return 0;
27 | }
28 |
29 | public int solution2(String S) {
30 | int leftBracketNum = 0;
31 | for (int i = 0; i < S.length(); i++) {
32 | if (S.charAt(i) == '(') {
33 | leftBracketNum++;
34 | } else {
35 | if (leftBracketNum == 0) {
36 | return 0;
37 | }
38 | leftBracketNum--;
39 | }
40 | }
41 | return leftBracketNum == 0 ? 1 : 0;
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/com/codility/lessons/Sorting/Distinct.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.Sorting;
2 |
3 | import java.util.Arrays;
4 | import java.util.HashSet;
5 | import java.util.Set;
6 |
7 | /**
8 | * Compute number of distinct values in an array.
9 | */
10 | public class Distinct {
11 | public int solution1(int[] A) {
12 | Set numberSet = new HashSet();
13 | for (int number : A) {
14 | numberSet.add(number);
15 | }
16 | return numberSet.size();
17 | }
18 |
19 | public int solution2(int[] A) {
20 | int N = A.length;
21 | if (N == 0)
22 | return 0;
23 | // the built-in sorting function performs O(n*log(n)) time complexity
24 | // even in the worst case
25 | Arrays.sort(A);
26 | int num = 1;
27 | int preDist = A[0];
28 | for (int i = 1; i < N; i++) {
29 | // add 1 to the number when there is a bigger element.
30 | if (A[i] != preDist) {
31 | preDist = A[i];
32 | num++;
33 | }
34 | }
35 | return num;
36 | }
37 |
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/codility/lessons/Arrays/OddOccurrencesInArray.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.Arrays;
2 | /**
3 | * *
4 | */
5 |
6 | public class OddOccurrencesInArray {
7 |
8 | public static int solution(int[] A) {
9 | int unpaired = 0;
10 | for (int number : A) {
11 | printBinaryFormat(number);
12 | System.out.println(" number===>"+number);
13 | unpaired ^= number;
14 | printBinaryFormat(unpaired);
15 | System.out.println(" unpaired===>"+unpaired);
16 | System.out.println("<=========>");
17 | }
18 | return unpaired;
19 | }
20 |
21 | public static void main(String[] args) {
22 | int[] A = {9,3,9,3,9,7,9};
23 |
24 | int res = solution(A);
25 | printBinaryFormat(res);
26 | System.out.println(" res===>"+res);
27 |
28 | //https://codility.com/demo/results/trainingNRQ4RE-4T9/
29 | }
30 | public static void printBinaryFormat(int number){
31 | int binary[] = new int[25];
32 | int index = 0;
33 | while(number > 0){
34 | binary[index++] = number%2;
35 | number = number/2;
36 | }
37 | for(int i = index-1;i >= 0;i--){
38 | System.out.print(binary[i]);
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/com/codility/lessons/Sorting/Triangle.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.Sorting;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Determine whether a triangle can be built from a given set of edges.
7 | *
8 | * @author Sunil
9 | *
10 | */
11 | public class Triangle {
12 |
13 | public int solution1(int[] A) {
14 | Arrays.sort(A);
15 | System.out.println("Lenght Of Array =" + A.length);
16 | for (int i = 0; i < A.length - 2; i++) {
17 | System.out.println("A[" + i + "] + A[" + (i + 1) + "] > " + "A[" + (i + 2) + "]");
18 | if ((long) A[i] + A[i + 1] > A[i + 2]) {
19 | System.out.println("A[" + i + "] + A[" + (i + 1) + "] > " + "A[" + (i + 2) + "]");
20 | System.out.println("Triplet is (" + i + ", " + (i + 1) + ", " + (i + 2) + ")");
21 | return 1;
22 | }
23 | }
24 | return 0;
25 | }
26 |
27 | public int solution2(int[] A) {
28 | int N = A.length;
29 | if (N < 3)
30 | return 0;
31 | Arrays.sort(A);
32 | for (int i = 0; i < N - 2; i++) {
33 | if (A[i] > 0 && A[i] > A[i + 2] - A[i + 1]) {
34 | System.out.println("Triplet is (" + i + ", " + (i + 2) + ", " + (i + 1) + ")");
35 | return 1;
36 | }
37 | }
38 | return 0;
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/com/codility/lessons/StacksQueues/StoneWall.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.StacksQueues;
2 |
3 | import java.util.Arrays;
4 | import java.util.Stack;
5 |
6 | public class StoneWall {
7 | public int solution1(int[] H) {
8 | int[] heights = Arrays.copyOf(H, H.length + 1);
9 | Stack increasingHeights = new Stack();
10 | int blockNum = 0;
11 | for (int height : heights) {
12 | while (!increasingHeights.empty() && increasingHeights.peek() >= height) {
13 | if (increasingHeights.peek() > height) {
14 | blockNum++;
15 | }
16 | increasingHeights.pop();
17 | }
18 | increasingHeights.push(height);
19 | }
20 | return blockNum;
21 | }
22 |
23 | public int solution2(int[] H) {
24 | int N = H.length;
25 | int[] stack = new int[N];
26 | int num = 0;
27 | stack[num++] = H[0];
28 | int result = 1;
29 | for (int i = 1; i < N; i++) {
30 | // store the stonewall in ascending order and pop out the larger
31 | // stonewall than the current stonewall
32 | while (num > 0 && stack[num - 1] > H[i]) {
33 | num--;
34 | }
35 | // if the stack is empty or the top of stack isn't equal to the
36 | // current stonewall, then we should push the current stonewall in
37 | // the stack and add 1 to the result.
38 | if (num == 0 || stack[num - 1] != H[i]) {
39 | stack[num++] = H[i];
40 | result++;
41 | }
42 | }
43 | return result;
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/com/codility/utils/CommonUtils.java:
--------------------------------------------------------------------------------
1 | package com.codility.utils;
2 |
3 | public class CommonUtils {
4 |
5 | public static int[][] randomMatrix(int M, int N, int min, int max) {
6 | int[][] matrix = new int[M][N];
7 | for (int i = 0; i < M; i++) {
8 | for (int j = 0; j < N; j++) {
9 | matrix[i][j] = randomIntInRange(min, max);
10 | }
11 | }
12 | return matrix;
13 | }
14 |
15 | public static int[] randomArray(int N, int min, int max) {
16 | int[] array = new int[N];
17 | for (int j = 0; j < N; j++) {
18 | array[j] = randomIntInRange(min, max);
19 | }
20 | return array;
21 | }
22 |
23 | public static int randomInt(int n) {
24 | return (int) (Math.random() * n);
25 | }
26 |
27 | public static int randomIntInRange(int min, int max) {
28 | return randomInt(max + 1 - min) + min;
29 | }
30 |
31 | public static void printIntArray(int[] array) {
32 | for (int i = 0; i < array.length; i++) {
33 | System.out.print(array[i] + " ");
34 | }
35 | System.out.println("");
36 | }
37 |
38 | public static String arrayToString(int[] array) {
39 | if (array == null)
40 | return "";
41 | return arrayToString(array, 0, array.length - 1);
42 | }
43 |
44 | public static String arrayToString(int[] array, int start, int end) {
45 | StringBuilder sb = new StringBuilder();
46 | for (int i = start; i <= end; i++) {
47 | int v = array[i];
48 | sb.append(v + ", ");
49 | }
50 | return sb.toString();
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/src/test/java/com/codility/lessons/StacksQueues/StoneWallTest.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.StacksQueues;
2 |
3 | import org.junit.After;
4 | import org.junit.Before;
5 | import org.junit.BeforeClass;
6 | import org.junit.Rule;
7 | import org.junit.Test;
8 | import org.junit.rules.Timeout;
9 | import org.junit.runner.RunWith;
10 | import org.slf4j.Logger;
11 | import org.slf4j.LoggerFactory;
12 | import org.springframework.test.context.junit4.SpringRunner;
13 |
14 | import com.codility.lessons.CountingElements.PermutationCheckTest;
15 |
16 | @RunWith(SpringRunner.class)
17 | public class StoneWallTest {
18 |
19 | private static Logger LOG = LoggerFactory.getLogger(PermutationCheckTest.class);
20 |
21 | static StoneWall stoneWall;
22 |
23 | @Rule
24 | public Timeout globalTimeout = Timeout.seconds(1);
25 |
26 | @BeforeClass
27 | public static void setup() {
28 | stoneWall = new StoneWall();
29 | }
30 |
31 | static long start, end;
32 | static double diff;
33 |
34 | @Before
35 | public void start() {
36 | start = System.currentTimeMillis();
37 | LOG.info("start-->" + start);
38 | }
39 |
40 | @After
41 | public void end() {
42 | end = System.currentTimeMillis();
43 | LOG.info("end-->" + end);
44 |
45 | diff = end - start;
46 | LOG.info("millis-->" + (diff));// millis
47 | LOG.info("seconds-->" + (diff / 1000));// seconds
48 | }
49 |
50 | @Test
51 | public void solution1Test() {
52 |
53 | // int res = stoneWall.solution1( );
54 | // assertEquals(res, 1);
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/test/java/com/codility/lessons/StacksQueues/BracketsTest.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.StacksQueues;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.After;
6 | import org.junit.Before;
7 | import org.junit.BeforeClass;
8 | import org.junit.Rule;
9 | import org.junit.Test;
10 | import org.junit.rules.Timeout;
11 | import org.junit.runner.RunWith;
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 | import org.springframework.test.context.junit4.SpringRunner;
15 |
16 | import com.codility.lessons.CountingElements.PermutationCheckTest;
17 |
18 | @RunWith(SpringRunner.class)
19 | public class BracketsTest {
20 |
21 | private static Logger LOG = LoggerFactory.getLogger(PermutationCheckTest.class);
22 |
23 | static Brackets brackets;
24 |
25 | @Rule
26 | public Timeout globalTimeout = Timeout.seconds(1);
27 |
28 | @BeforeClass
29 | public static void setup() {
30 | brackets = new Brackets();
31 | }
32 |
33 | static long start, end;
34 | static double diff;
35 |
36 | @Before
37 | public void start() {
38 | start = System.currentTimeMillis();
39 | LOG.info("start-->" + start);
40 | }
41 |
42 | @After
43 | public void end() {
44 | end = System.currentTimeMillis();
45 | LOG.info("end-->" + end);
46 |
47 | diff = end - start;
48 | LOG.info("millis-->" + (diff));// millis
49 | LOG.info("seconds-->" + (diff / 1000));// seconds
50 | }
51 |
52 | @Test
53 | public void solution1Test() {
54 | String s = "{[()()]}";
55 |
56 | int res = brackets.solution1(s);
57 | assertEquals(res, 0);
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/src/test/java/com/codility/lessons/StacksQueues/NestingTest.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.StacksQueues;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.After;
6 | import org.junit.Before;
7 | import org.junit.BeforeClass;
8 | import org.junit.Rule;
9 | import org.junit.Test;
10 | import org.junit.rules.Timeout;
11 | import org.junit.runner.RunWith;
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 | import org.springframework.test.context.junit4.SpringRunner;
15 |
16 | import com.codility.lessons.CountingElements.PermutationCheckTest;
17 |
18 | @RunWith(SpringRunner.class)
19 | public class NestingTest {
20 |
21 | private static Logger LOG = LoggerFactory.getLogger(PermutationCheckTest.class);
22 |
23 | static Nesting nesting;
24 |
25 | @Rule
26 | public Timeout globalTimeout = Timeout.seconds(1);
27 |
28 | @BeforeClass
29 | public static void setup() {
30 | nesting = new Nesting();
31 | }
32 |
33 | static long start, end;
34 | static double diff;
35 |
36 | @Before
37 | public void start() {
38 | start = System.currentTimeMillis();
39 | LOG.info("start-->" + start);
40 | }
41 |
42 | @After
43 | public void end() {
44 | end = System.currentTimeMillis();
45 | LOG.info("end-->" + end);
46 |
47 | diff = end - start;
48 | LOG.info("millis-->" + (diff));// millis
49 | LOG.info("seconds-->" + (diff / 1000));// seconds
50 | }
51 |
52 | @Test
53 | public void solution1Test() {
54 | String s = "(()(())())";
55 |
56 | int res = nesting.solution1(s);
57 | assertEquals(res, 1);
58 | }
59 |
60 | @Test
61 | public void solution2Test() {
62 | String s = "(()(())())";
63 |
64 | int res = nesting.solution2(s);
65 | assertEquals(res, 1);
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/src/test/java/com/codility/lessons/Sorting/NumberOfDiscIntersectionsTest.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.Sorting;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.After;
6 | import org.junit.Before;
7 | import org.junit.BeforeClass;
8 | import org.junit.Rule;
9 | import org.junit.Test;
10 | import org.junit.rules.Timeout;
11 | import org.junit.runner.RunWith;
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 | import org.springframework.test.context.junit4.SpringRunner;
15 |
16 | import com.codility.lessons.CountingElements.PermutationCheckTest;
17 |
18 | @RunWith(SpringRunner.class)
19 | public class NumberOfDiscIntersectionsTest {
20 | private static Logger LOG = LoggerFactory.getLogger(PermutationCheckTest.class);
21 |
22 | static NumberOfDiscIntersections numberOfDiscIntersections;
23 |
24 | @Rule
25 | public Timeout globalTimeout = Timeout.seconds(1);
26 |
27 | @BeforeClass
28 | public static void setup() {
29 | numberOfDiscIntersections = new NumberOfDiscIntersections();
30 | }
31 |
32 | static long start, end;
33 | static double diff;
34 |
35 | @Before
36 | public void start() {
37 | start = System.currentTimeMillis();
38 | LOG.debug("start-->" + start);
39 | }
40 |
41 | @After
42 | public void end() {
43 | end = System.currentTimeMillis();
44 | LOG.debug("end-->" + end);
45 |
46 | diff = end - start;
47 | LOG.info("millis-->" + (diff));// millis
48 | LOG.info("seconds-->" + (diff / 1000));// seconds
49 | }
50 |
51 | @Test
52 | public void solution1Test() {
53 | int[] A = new int[5];
54 | for (int i = 0; i < 5; i++) {
55 | A[i] = i + 100;
56 | LOG.info("A-->" + A[i]);
57 | }
58 |
59 | int res = numberOfDiscIntersections.solution1(A);
60 | assertEquals(res, 0);
61 | }
62 |
63 | @Test
64 | public void solution2Test() {
65 |
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/test/java/com/codility/lessons/Sorting/DistinctTest.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.Sorting;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.After;
6 | import org.junit.Before;
7 | import org.junit.BeforeClass;
8 | import org.junit.Rule;
9 | import org.junit.Test;
10 | import org.junit.rules.Timeout;
11 | import org.junit.runner.RunWith;
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 | import org.springframework.test.context.junit4.SpringRunner;
15 |
16 | import com.codility.lessons.CountingElements.PermutationCheckTest;
17 |
18 | /**
19 | * https://app.codility.com/demo/results/trainingKSZ5AP-TS8/
20 | *
21 | * @author Sunil
22 | *
23 | */
24 | @RunWith(SpringRunner.class)
25 | public class DistinctTest {
26 |
27 | private static Logger LOG = LoggerFactory.getLogger(PermutationCheckTest.class);
28 |
29 | static Distinct distinct;
30 |
31 | @Rule
32 | public Timeout globalTimeout = Timeout.seconds(1);
33 |
34 | @BeforeClass
35 | public static void setup() {
36 | distinct = new Distinct();
37 | }
38 |
39 | static long start, end;
40 | static double diff;
41 |
42 | @Before
43 | public void start() {
44 | start = System.currentTimeMillis();
45 | LOG.info("start-->" + start);
46 | }
47 |
48 | @After
49 | public void end() {
50 | end = System.currentTimeMillis();
51 | LOG.info("end-->" + end);
52 |
53 | diff = end - start;
54 | LOG.info("millis-->" + (diff));// millis
55 | LOG.info("seconds-->" + (diff / 1000));// seconds
56 | }
57 |
58 | @Test
59 | public void solution1Test() {
60 | int[] A = new int[5];
61 | for (int i = 0; i < 5; i++) {
62 | A[i] = i + 100;
63 | LOG.info("A-->" + A[i]);
64 | }
65 |
66 | int res = distinct.solution1(A);
67 | assertEquals(res, 0);
68 | }
69 |
70 | @Test
71 | public void solution2Test() {
72 |
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/src/test/java/com/codility/lessons/Sorting/TriangleTest.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.Sorting;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.After;
6 | import org.junit.Before;
7 | import org.junit.BeforeClass;
8 | import org.junit.Rule;
9 | import org.junit.Test;
10 | import org.junit.rules.Timeout;
11 | import org.junit.runner.RunWith;
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 | import org.springframework.test.context.junit4.SpringRunner;
15 |
16 | import com.codility.lessons.CountingElements.PermutationCheckTest;
17 |
18 | /**
19 | * https://app.codility.com/demo/results/trainingCEY5VM-9WC/
20 | *
21 | * @author Sunil
22 | *
23 | */
24 | @RunWith(SpringRunner.class)
25 | public class TriangleTest {
26 | private static Logger LOG = LoggerFactory.getLogger(PermutationCheckTest.class);
27 | static Triangle triangle;
28 | @Rule
29 | public Timeout globalTimeout = Timeout.seconds(1);
30 |
31 | @BeforeClass
32 | public static void setup() {
33 | triangle = new Triangle();
34 | }
35 |
36 | static long start, end;
37 | static double diff;
38 |
39 | @Before
40 | public void start() {
41 | start = System.currentTimeMillis();
42 | LOG.info("start-->" + start);
43 | }
44 |
45 | @After
46 | public void end() {
47 | end = System.currentTimeMillis();
48 | LOG.info("end-->" + end);
49 |
50 | diff = end - start;
51 | LOG.info("millis-->" + (diff));// millis
52 | LOG.info("seconds-->" + (diff / 1000));// seconds
53 | }
54 |
55 | @Test
56 | public void solution1Test() {
57 | int[] A = new int[5];
58 | for (int i = 0; i < 5; i++) {
59 | A[i] = i + 100;
60 | }
61 |
62 | int res = triangle.solution1(A);
63 | assertEquals(res, 1);
64 | }
65 |
66 | @Test
67 | public void solution2Test() {
68 | int[] A = new int[5];
69 | for (int i = 0; i < 5; i++) {
70 | A[i] = i + 100;
71 | }
72 |
73 | int res = triangle.solution2(A);
74 | assertEquals(res, 1);
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/test/java/com/codility/lessons/Sorting/MaxProductOfThreeTest.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.Sorting;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.After;
6 | import org.junit.Before;
7 | import org.junit.BeforeClass;
8 | import org.junit.Rule;
9 | import org.junit.Test;
10 | import org.junit.rules.Timeout;
11 | import org.junit.runner.RunWith;
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 | import org.springframework.test.context.junit4.SpringRunner;
15 |
16 | import com.codility.lessons.CountingElements.PermutationCheckTest;
17 |
18 | /**
19 | * https://app.codility.com/demo/results/trainingJXXKP9-4EM/
20 | *
21 | * @author Sunil
22 | *
23 | */
24 | @RunWith(SpringRunner.class)
25 | public class MaxProductOfThreeTest {
26 |
27 | private static Logger LOG = LoggerFactory.getLogger(PermutationCheckTest.class);
28 |
29 | static MaxProductOfThree maxProductOfThree;
30 |
31 | @Rule
32 | public Timeout globalTimeout = Timeout.seconds(1);
33 |
34 | @BeforeClass
35 | public static void setup() {
36 | maxProductOfThree = new MaxProductOfThree();
37 | }
38 |
39 | static long start, end;
40 | static double diff;
41 |
42 | @Before
43 | public void start() {
44 | start = System.currentTimeMillis();
45 | LOG.debug("start-->" + start);
46 | }
47 |
48 | @After
49 | public void end() {
50 | end = System.currentTimeMillis();
51 | LOG.debug("end-->" + end);
52 |
53 | diff = end - start;
54 | LOG.info("millis-->" + (diff));// millis
55 | LOG.info("seconds-->" + (diff / 1000));// seconds
56 | }
57 |
58 | @Test
59 | public void solution1Test() {
60 | // int[] A = CommonUtils.randomArray(5, 1, 10);
61 | // CommonUtils.printIntArray(A);
62 | int[] A = { 2, 8, 5, 2, 4 };
63 | int res = maxProductOfThree.solution1(A);
64 | LOG.info("res-->" + res);
65 |
66 | assertEquals(res, 160);
67 | }
68 |
69 | @Test
70 | public void solution2Test() {
71 | int[] A = { 2, 8, 5, 2, 4 };
72 | int res = maxProductOfThree.solution2(A);
73 | LOG.info("res-->" + res);
74 |
75 | assertEquals(res, 160);
76 | }
77 |
78 | @Test
79 | public void solution3Test() {
80 | int[] A = { -3, 1, 2, -2, 5, 6 };
81 | int res = maxProductOfThree.solution3(A);
82 | LOG.info("res-->" + res);
83 |
84 | assertEquals(res, 60);
85 | }
86 |
87 | }
88 |
--------------------------------------------------------------------------------
/src/test/java/com/codility/lessons/CountingElements/PermutationCheckTest.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.CountingElements;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.After;
6 | import org.junit.Before;
7 | import org.junit.BeforeClass;
8 | import org.junit.Rule;
9 | import org.junit.Test;
10 | import org.junit.rules.Timeout;
11 | import org.junit.runner.RunWith;
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 | import org.springframework.test.context.junit4.SpringRunner;
15 |
16 | @RunWith(SpringRunner.class)
17 | public class PermutationCheckTest {
18 | private static Logger LOG = LoggerFactory.getLogger(PermutationCheckTest.class);
19 |
20 | static PermutationCheck permutationCheck;
21 |
22 | @Rule
23 | public Timeout globalTimeout = Timeout.seconds(1);
24 |
25 | @BeforeClass
26 | public static void setup() {
27 | permutationCheck = new PermutationCheck();
28 | }
29 |
30 | static long start, end;
31 | static double diff;
32 |
33 | @Before
34 | public void start() {
35 | start = System.currentTimeMillis();
36 | LOG.info("start-->" + start);
37 | }
38 |
39 | @After
40 | public void end() {
41 | end = System.currentTimeMillis();
42 | LOG.info("end-->" + end);
43 |
44 | diff = end - start;
45 | LOG.info("millis-->" + (diff));// millis
46 | LOG.info("seconds-->" + (diff / 1000));// seconds
47 | }
48 |
49 | @Test
50 | public void permutationCheckTest() {
51 |
52 | int[] A = new int[5];
53 | for (int i = 0; i < 5; i++) {
54 | A[i] = i + 100;
55 | LOG.info("A-->" + A[i]);
56 | }
57 |
58 | int res = permutationCheck.solution(A);
59 | assertEquals(res, 0);
60 |
61 | A = new int[100];
62 | for (int i = 99; i >= 0; i--) {
63 | A[i] = i;
64 | // LOG.info("A-->" + A[i] );
65 | }
66 | res = permutationCheck.solution(A);
67 | assertEquals(res, 0);
68 |
69 | A = new int[100];
70 | for (int i = 99; i >= 0; i--) {
71 | A[i] = i;
72 | // LOG.info("A-->" + A[i] );
73 | }
74 |
75 | res = permutationCheck.solution(A);
76 | assertEquals(res, 0);
77 |
78 | A = new int[100];
79 | for (int i = 0; i < 100; i++) {
80 | A[i] = i;
81 | // LOG.info("A-->" + A[i] );
82 | }
83 |
84 | res = permutationCheck.solution(A);
85 | assertEquals(res, 0);
86 |
87 | A = new int[5];
88 | for (int i = 0; i < 5; i++) {
89 | A[i] = i + 1;
90 | // LOG.info("A-->" + A[i] );
91 | }
92 |
93 | res = permutationCheck.solution(A);
94 | assertEquals(res, 1);
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/src/main/java/com/codility/lessons/Sorting/MaxProductOfThree.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.Sorting;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Maximize A[P] * A[Q] * A[R] for any triplet (P, Q, R).
7 | *
8 | * @author Sunil
9 | *
10 | */
11 | public class MaxProductOfThree {
12 |
13 | public int solution1(int[] A) {
14 | Arrays.sort(A);
15 | int N = A.length;
16 | return Math.max(A[N - 3] * A[N - 2] * A[N - 1], A[0] * A[1] * A[N - 1]);
17 | }
18 |
19 | public int solution2(int[] A) {
20 | int N = A.length;
21 | // the worst-case time complexity is O(N*log(N))
22 | Arrays.sort(A);
23 | // the max product of three elements is the product of the last three
24 | // elements in the sorted array or the product of the first two elements
25 | // and the last element if the first two elements are negatives.
26 | return Math.max(A[0] * A[1] * A[N - 1], A[N - 3] * A[N - 2] * A[N - 1]);
27 | }
28 |
29 | public int solution3(int[] A) {
30 | // the variable stores the minimal negative element
31 | int negativeMin = 0;
32 | // the variable stores the second minimal negative element
33 | int negativeSecond = 0;
34 | // the variable stores the third maximal element
35 | int thirdMax = -1000;
36 | // the variable stores the second maximal element
37 | int secondMax = -1000;
38 | // the variable stores the maximal element
39 | int maxValue = -1000;
40 | // get the five variables above in O(N) time complexity
41 | for (int element : A) {
42 | if (element < negativeMin) {
43 | negativeSecond = negativeMin;
44 | negativeMin = element;
45 | } else if (element < negativeSecond)
46 | negativeSecond = element;
47 | if (element > maxValue) {
48 | thirdMax = secondMax;
49 | secondMax = maxValue;
50 | maxValue = element;
51 | } else if (element > secondMax) {
52 | thirdMax = secondMax;
53 | secondMax = element;
54 | } else if (element > thirdMax)
55 | thirdMax = element;
56 | }
57 | // the product of the three maximal elements
58 | int maxProduct = thirdMax * secondMax * maxValue;
59 | // the number of negative elements is more than 2
60 | if (negativeSecond != 0)
61 | // the result is either the product of the three maximal elements or
62 | // the product of the two minimal negative elements and the maximal
63 | // positive element.
64 | return Math.max(negativeMin * negativeSecond * maxValue, maxProduct);
65 | // the number of negative elements is less than 2
66 | else
67 | return maxProduct;
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/com/codility/lessons/Arrays/CyclicRotation.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.Arrays;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 |
7 | */
8 | public class CyclicRotation {
9 |
10 | public static void main(String[] args) {
11 |
12 | //https://codility.com/demo/results/trainingUBWFTE-G5D/
13 | int[] A = {-3, 8, 9, -7, 6} ;
14 | int K = 3;
15 |
16 | int[] sol1 = solution1(A,K);
17 | System.out.println("sol1-->"+Arrays.toString(sol1));
18 |
19 | int[] sol2 = solution2(A,K);
20 | System.out.println("sol2-->"+Arrays.toString(sol2));
21 |
22 | int[] sol3 = solution3(A,K);
23 | System.out.println("sol3-->"+Arrays.toString(sol3));
24 |
25 |
26 | int[] sol4 = solution4(A,K);
27 | System.out.println("sol4-->"+Arrays.toString(sol4));
28 | }
29 |
30 |
31 | public static int [] solution1(int [] A, int K) {
32 |
33 | int size = A.length;
34 | int ret[] = new int [size];
35 |
36 | if (K < 0 || K > 100 || size == 0) {
37 | return ret;
38 | }
39 |
40 | if (size == 1) {
41 | return A;
42 | }
43 |
44 | for (int i = 0; i < size; i++) {
45 | ret[(i + K) % size] = A[i];
46 |
47 | //when i=0 then (0+3)=3 =>(3 modulo 5)= 3
48 | }
49 |
50 | return ret;
51 | }
52 |
53 | public static int [] solution2(int [] A, int K)
54 | {
55 | int N = A.length;
56 | if (N==0)
57 | return A;
58 | if (K>=N)
59 | K %= N;
60 | if (K==0)
61 | return A;
62 | int [] rotA = new int [N];
63 | for (int i=0; i"+result);
40 |
41 | result = solution(input);
42 | System.out.print("result11--->"+result);
43 |
44 | }
45 |
46 | static int missingElem(int[] A){ // Function to Find Missing Element
47 | long sum = 0; // Will Hold Sum of All Numbers from 1 to N+1
48 | long arraysum = 0; // Will Hold Sum of All Numbers in Array
49 | long missing = 0; // Will Hold Missing Value
50 |
51 | for (int i = 0; i < A.length; i++) {// Get Sum of All Numbers from 1 to N+1, and Array
52 | sum += (i + 1);
53 | arraysum += A[i];
54 | }
55 | sum += A.length + 1; // Add Last Number in Range (N+1)
56 | missing = sum - arraysum; // Subtract Sum of Array from Sum of Range to get Missing Value
57 | return (int) missing; // Return Missing Value
58 | }
59 |
60 | //https://codility.com/demo/results/trainingPRHEBN-NCZ/
61 | static int solution(int[] data) {
62 | long N = data.length + 1;
63 | long total = (N * (N + 1)) / 2;
64 | long sum = 0L;
65 | for (int i : data) {
66 | sum += i;
67 | }
68 | return (int) (total - sum);
69 | }
70 | static int solution1(int[] A) {
71 | if(A == null){
72 | return 0;
73 | }
74 | long arraySum = Arrays.stream(A).asLongStream().sum();
75 | long N = A.length+1;
76 | long expectedSum = (N*(N+1))/2;
77 | return (int)(expectedSum-arraySum);
78 | }
79 |
80 |
81 | }
82 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | com.codility
7 | Codility-Practice
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | Codility-Practice
12 | Codility for Programmers
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.0.0.M7
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter
31 |
32 |
33 |
34 | org.projectlombok
35 | lombok
36 | true
37 |
38 |
39 | org.springframework.boot
40 | spring-boot-starter-test
41 | test
42 |
43 |
44 |
45 |
46 |
47 |
48 | org.springframework.boot
49 | spring-boot-maven-plugin
50 |
51 |
52 |
53 |
54 |
55 |
56 | spring-snapshots
57 | Spring Snapshots
58 | https://repo.spring.io/snapshot
59 |
60 | true
61 |
62 |
63 |
64 | spring-milestones
65 | Spring Milestones
66 | https://repo.spring.io/milestone
67 |
68 | false
69 |
70 |
71 |
72 |
73 |
74 |
75 | spring-snapshots
76 | Spring Snapshots
77 | https://repo.spring.io/snapshot
78 |
79 | true
80 |
81 |
82 |
83 | spring-milestones
84 | Spring Milestones
85 | https://repo.spring.io/milestone
86 |
87 | false
88 |
89 |
90 |
91 |
92 |
93 |
94 |
--------------------------------------------------------------------------------
/src/main/java/com/codility/lessons/Sorting/NumberOfDiscIntersections.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.Sorting;
2 |
3 | import java.util.Arrays;
4 | import java.util.Comparator;
5 |
6 | /**
7 | * Compute the number of intersections in a sequence of discs.
8 | *
9 | * @url https://app.codility.com/programmers/lessons/6-sorting/number_of_disc_intersections/
10 | *
11 | * @author Sunil
12 | *
13 | */
14 | public class NumberOfDiscIntersections {
15 |
16 | public int solution1(int[] A) {
17 | int N = A.length;
18 | if (N < 2)
19 | return 0;
20 | // intervals stores the two elements : i - A[i] and i + A[i]
21 | long[][] intervals = new long[N][2];
22 | for (int i = 0; i < N; i++) {
23 | intervals[i][0] = (long) i - A[i];
24 | intervals[i][1] = (long) i + A[i];
25 | }
26 | // using the lambda expression to sort a two dimensional array by the
27 | // intervals left end in ascending order
28 | Arrays.sort(intervals, (long[] a, long[] b) -> Long.signum(a[0] - b[0]));
29 | int result = 0;
30 | for (int i = 0; i < N - 1; i++) {
31 | // using the intervals' right end as the key value of binary search
32 | long rightEnd = intervals[i][1];
33 | int binarySearchLeft = i + 1;
34 | int binarySearchRight = N - 1;
35 | int resultIndex = i;
36 | // using the binary search to find the number of intersections
37 | while (binarySearchLeft <= binarySearchRight) {
38 | int binarySearchMid = (binarySearchLeft + binarySearchRight) / 2;
39 | if (intervals[binarySearchMid][0] <= rightEnd) {
40 | resultIndex = binarySearchMid;
41 | binarySearchLeft = binarySearchMid + 1;
42 | } else
43 | binarySearchRight = binarySearchMid - 1;
44 | }
45 | // count the number of intersections
46 | result += (resultIndex - i);
47 | if (result > 10000000)
48 | return -1;
49 | }
50 | return result;
51 | }
52 |
53 | public int solution2(int[] A) {
54 | int N = A.length;
55 | if (N < 2)
56 | return 0;
57 | // stores the number of discs which start at each point
58 | int[] discStart = new int[N];
59 | // stores the number of discs which end at each point
60 | int[] discEnd = new int[N];
61 | for (int i = 0; i < N; i++) {
62 | discStart[Math.max(0, i - A[i])]++;
63 | // the result of i + A[i] could be over the max integer in java and
64 | // it will become a negative integer.
65 | if (i + A[i] < 0)
66 | discEnd[N - 1]++;
67 | else
68 | discEnd[Math.min(N - 1, i + A[i])]++;
69 | }
70 | // the number of discs which haven't been calculated at a very point
71 | int unCalcDiscNo = 0;
72 | int result = 0;
73 | for (int i = 0; i < N; i++) {
74 | if (discStart[i] > 0) {
75 | // calculate the product of the number of discs that haven't
76 | // been calculated and the number of started discs at this point
77 | result += unCalcDiscNo * discStart[i];
78 | // calculate the number of intersections of the started discs at
79 | // this point, the algorithm is 1+2+...+N = N*(N-1)/2
80 | result += discStart[i] * (discStart[i] - 1) / 2;
81 | if (result > 10000000)
82 | return -1;
83 | // add the number of start discs to unCalcDiscNo
84 | unCalcDiscNo += discStart[i];
85 | }
86 | if (discEnd[i] > 0)
87 | // subtract the calculated discs from unCalcDiscNo
88 | unCalcDiscNo -= discEnd[i];
89 | }
90 | return result;
91 | }
92 |
93 | static final int LIMIT = 10000000;
94 |
95 | public int solution3(int[] A) {
96 | Point[] points = new Point[A.length * 2];
97 | for (int i = 0; i < A.length; i++) {
98 | points[i * 2] = new Point((long) i - A[i], Type.LOWER);
99 | points[i * 2 + 1] = new Point((long) i + A[i], Type.UPPER);
100 | }
101 |
102 | Arrays.sort(points, new PointComparator());
103 |
104 | int intersectNum = 0;
105 | int openedNum = 0;
106 | for (Point point : points) {
107 | if (point.type.equals(Type.LOWER)) {
108 | intersectNum += openedNum;
109 | if (intersectNum > LIMIT) {
110 | return -1;
111 | }
112 | openedNum++;
113 | } else {
114 | openedNum--;
115 | }
116 | }
117 | return intersectNum;
118 | }
119 | }
120 |
121 | class PointComparator implements Comparator {
122 | @Override
123 | public int compare(Point p1, Point p2) {
124 | if (p1.y != p2.y) {
125 | return (int) Math.signum(p1.y - p2.y);
126 | }
127 | return p1.type.equals(Type.LOWER) ? -1 : 1;
128 | }
129 | }
130 |
131 | class Point {
132 | long y;
133 | Type type;
134 |
135 | Point(long y, Type type) {
136 | this.y = y;
137 | this.type = type;
138 | }
139 | }
140 |
141 | enum Type {
142 | LOWER, UPPER
143 |
144 | }
145 |
--------------------------------------------------------------------------------
/src/test/java/com/codility/lessons/BinaryGap/BinaryGapTest.java:
--------------------------------------------------------------------------------
1 | package com.codility.lessons.BinaryGap;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertNotNull;
5 |
6 | import org.junit.After;
7 | import org.junit.Before;
8 | import org.junit.BeforeClass;
9 | import org.junit.Rule;
10 | import org.junit.Test;
11 | import org.junit.rules.Timeout;
12 | import org.junit.runner.RunWith;
13 | import org.slf4j.Logger;
14 | import org.slf4j.LoggerFactory;
15 | import org.springframework.test.context.junit4.SpringRunner;
16 |
17 | /**
18 | * https://app.codility.com/demo/results/trainingABYQAR-B7W/
19 | */
20 | @RunWith(SpringRunner.class)
21 | public class BinaryGapTest {
22 | private static Logger LOG = LoggerFactory.getLogger(BinaryGapTest.class);
23 |
24 | static BinaryGap binaryGap;
25 |
26 | @Rule
27 | public Timeout globalTimeout = Timeout.seconds(10);
28 |
29 | @BeforeClass
30 | public static void setup() {
31 | binaryGap = new BinaryGap();
32 | }
33 |
34 | long start, end, diff;
35 |
36 | @Before
37 | public void start() {
38 | start = System.currentTimeMillis();
39 | }
40 |
41 | @After
42 | public void end() {
43 | end = System.currentTimeMillis();
44 | diff = end - start;
45 | LOG.info("diff-->" + diff);
46 | }
47 |
48 | @Test
49 | public void solutionTest() {
50 |
51 | int n = 1041;// 10000010001
52 | int res = binaryGap.solution(n);
53 | LOG.info("res-->" + res);
54 |
55 | assertNotNull(res);
56 | assertEquals(res, 5);
57 |
58 | // LOG.info("diff-->"+diff);
59 |
60 | // example2 example test n=15=1111_2
61 | res = binaryGap.solution(15);
62 | LOG.info("15--->" + res);
63 | assertEquals(res, 0);
64 |
65 | // extremes n=1, n=5=101_2 and n=2147483647=2**31-1
66 | res = binaryGap.solution(1);
67 | LOG.info("1--->" + res);
68 | assertEquals(res, 0);
69 |
70 | res = binaryGap.solution(5);
71 | LOG.info("5--->" + res);
72 | assertEquals(res, 1);
73 |
74 | res = binaryGap.solution(2147483647);
75 | LOG.info("2147483647--->" + res);
76 | assertEquals(res, 0);
77 |
78 | // trailing_zeroes n=6=110_2 and n=328=101001000_2
79 | res = binaryGap.solution(6);
80 | LOG.info("6(110_2)--->" + res);
81 | assertEquals(res, 0);
82 |
83 | res = binaryGap.solution(328);
84 | LOG.info("328(101001000_2)--->" + res);
85 | assertEquals(res, 2);
86 |
87 | res = binaryGap.solution(101001000_2);
88 | LOG.info("res--->" + res);
89 | assertEquals(res, 4);
90 |
91 | // power_of_2 n=5=101_2, n=16=2**4 and n=1024=2**10
92 | res = binaryGap.solution(5);
93 | LOG.info("5=101_2--->" + res);
94 | assertEquals(res, 1);
95 |
96 | res = binaryGap.solution(16);
97 | LOG.info("16=2**4--->" + res);
98 | assertEquals(res, 0);
99 |
100 | res = binaryGap.solution(1024);
101 | LOG.info("1024=2**10--->" + res);
102 | assertEquals(res, 0);
103 |
104 | // simple1 n=9=1001_2 and n=11=1011_2
105 | res = binaryGap.solution(9);
106 | LOG.info("9=1001_2--->" + res);
107 | assertEquals(res, 2);
108 |
109 | res = binaryGap.solution(11);
110 | LOG.info("11=1011_2--->" + res);
111 | assertEquals(res, 1);
112 |
113 | // simple2 n=19=10011 and n=42=101010_2
114 | res = binaryGap.solution(19);
115 | LOG.info("19=10011--->" + res);
116 | assertEquals(res, 2);
117 |
118 | res = binaryGap.solution(42);
119 | LOG.info("42=101010_2--->" + res);
120 | assertEquals(res, 1);
121 |
122 | // simple3 n=1162=10010001010_2 and n=5=101_2
123 | res = binaryGap.solution(1162);
124 | LOG.info("1162=10010001010_2--->" + res);
125 | assertEquals(res, 3);
126 |
127 | res = binaryGap.solution(5);
128 | LOG.info("5=101_2--->" + res);
129 | assertEquals(res, 1);
130 |
131 | // medium1 n=51712=110010100000000_2 and n=20=10100_2
132 | res = binaryGap.solution(51712);
133 | LOG.info("51712=110010100000000_2--->" + res);
134 | assertEquals(res, 2);
135 |
136 | res = binaryGap.solution(20);
137 | LOG.info("20=10100_2--->" + res);
138 | assertEquals(res, 1);
139 | }
140 |
141 |
142 | @Test(timeout = 500)
143 | public void timeTest() {
144 | // extremes n=1, n=5=101_2 and n=2147483647=2**31-1
145 | int res = binaryGap.solution(2147483647);
146 | LOG.info("1--->" + res);
147 |
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/mvnw.cmd:
--------------------------------------------------------------------------------
1 | @REM ----------------------------------------------------------------------------
2 | @REM Licensed to the Apache Software Foundation (ASF) under one
3 | @REM or more contributor license agreements. See the NOTICE file
4 | @REM distributed with this work for additional information
5 | @REM regarding copyright ownership. The ASF licenses this file
6 | @REM to you under the Apache License, Version 2.0 (the
7 | @REM "License"); you may not use this file except in compliance
8 | @REM with the License. You may obtain a copy of the License at
9 | @REM
10 | @REM http://www.apache.org/licenses/LICENSE-2.0
11 | @REM
12 | @REM Unless required by applicable law or agreed to in writing,
13 | @REM software distributed under the License is distributed on an
14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | @REM KIND, either express or implied. See the License for the
16 | @REM specific language governing permissions and limitations
17 | @REM under the License.
18 | @REM ----------------------------------------------------------------------------
19 |
20 | @REM ----------------------------------------------------------------------------
21 | @REM Maven2 Start Up Batch script
22 | @REM
23 | @REM Required ENV vars:
24 | @REM JAVA_HOME - location of a JDK home dir
25 | @REM
26 | @REM Optional ENV vars
27 | @REM M2_HOME - location of maven2's installed home dir
28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
31 | @REM e.g. to debug Maven itself, use
32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34 | @REM ----------------------------------------------------------------------------
35 |
36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
37 | @echo off
38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
40 |
41 | @REM set %HOME% to equivalent of $HOME
42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
43 |
44 | @REM Execute a user defined script before this one
45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
49 | :skipRcPre
50 |
51 | @setlocal
52 |
53 | set ERROR_CODE=0
54 |
55 | @REM To isolate internal variables from possible post scripts, we use another setlocal
56 | @setlocal
57 |
58 | @REM ==== START VALIDATION ====
59 | if not "%JAVA_HOME%" == "" goto OkJHome
60 |
61 | echo.
62 | echo Error: JAVA_HOME not found in your environment. >&2
63 | echo Please set the JAVA_HOME variable in your environment to match the >&2
64 | echo location of your Java installation. >&2
65 | echo.
66 | goto error
67 |
68 | :OkJHome
69 | if exist "%JAVA_HOME%\bin\java.exe" goto init
70 |
71 | echo.
72 | echo Error: JAVA_HOME is set to an invalid directory. >&2
73 | echo JAVA_HOME = "%JAVA_HOME%" >&2
74 | echo Please set the JAVA_HOME variable in your environment to match the >&2
75 | echo location of your Java installation. >&2
76 | echo.
77 | goto error
78 |
79 | @REM ==== END VALIDATION ====
80 |
81 | :init
82 |
83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
84 | @REM Fallback to current working directory if not found.
85 |
86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
88 |
89 | set EXEC_DIR=%CD%
90 | set WDIR=%EXEC_DIR%
91 | :findBaseDir
92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
93 | cd ..
94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
95 | set WDIR=%CD%
96 | goto findBaseDir
97 |
98 | :baseDirFound
99 | set MAVEN_PROJECTBASEDIR=%WDIR%
100 | cd "%EXEC_DIR%"
101 | goto endDetectBaseDir
102 |
103 | :baseDirNotFound
104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
105 | cd "%EXEC_DIR%"
106 |
107 | :endDetectBaseDir
108 |
109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
110 |
111 | @setlocal EnableExtensions EnableDelayedExpansion
112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
114 |
115 | :endReadAdditionalConfig
116 |
117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
118 |
119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
121 |
122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
123 | if ERRORLEVEL 1 goto error
124 | goto end
125 |
126 | :error
127 | set ERROR_CODE=1
128 |
129 | :end
130 | @endlocal & set ERROR_CODE=%ERROR_CODE%
131 |
132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
136 | :skipRcPost
137 |
138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause
140 |
141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
142 |
143 | exit /B %ERROR_CODE%
144 |
--------------------------------------------------------------------------------
/mvnw:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # ----------------------------------------------------------------------------
3 | # Licensed to the Apache Software Foundation (ASF) under one
4 | # or more contributor license agreements. See the NOTICE file
5 | # distributed with this work for additional information
6 | # regarding copyright ownership. The ASF licenses this file
7 | # to you under the Apache License, Version 2.0 (the
8 | # "License"); you may not use this file except in compliance
9 | # with the License. You may obtain a copy of the License at
10 | #
11 | # http://www.apache.org/licenses/LICENSE-2.0
12 | #
13 | # Unless required by applicable law or agreed to in writing,
14 | # software distributed under the License is distributed on an
15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 | # KIND, either express or implied. See the License for the
17 | # specific language governing permissions and limitations
18 | # under the License.
19 | # ----------------------------------------------------------------------------
20 |
21 | # ----------------------------------------------------------------------------
22 | # Maven2 Start Up Batch script
23 | #
24 | # Required ENV vars:
25 | # ------------------
26 | # JAVA_HOME - location of a JDK home dir
27 | #
28 | # Optional ENV vars
29 | # -----------------
30 | # M2_HOME - location of maven2's installed home dir
31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven
32 | # e.g. to debug Maven itself, use
33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files
35 | # ----------------------------------------------------------------------------
36 |
37 | if [ -z "$MAVEN_SKIP_RC" ] ; then
38 |
39 | if [ -f /etc/mavenrc ] ; then
40 | . /etc/mavenrc
41 | fi
42 |
43 | if [ -f "$HOME/.mavenrc" ] ; then
44 | . "$HOME/.mavenrc"
45 | fi
46 |
47 | fi
48 |
49 | # OS specific support. $var _must_ be set to either true or false.
50 | cygwin=false;
51 | darwin=false;
52 | mingw=false
53 | case "`uname`" in
54 | CYGWIN*) cygwin=true ;;
55 | MINGW*) mingw=true;;
56 | Darwin*) darwin=true
57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
59 | if [ -z "$JAVA_HOME" ]; then
60 | if [ -x "/usr/libexec/java_home" ]; then
61 | export JAVA_HOME="`/usr/libexec/java_home`"
62 | else
63 | export JAVA_HOME="/Library/Java/Home"
64 | fi
65 | fi
66 | ;;
67 | esac
68 |
69 | if [ -z "$JAVA_HOME" ] ; then
70 | if [ -r /etc/gentoo-release ] ; then
71 | JAVA_HOME=`java-config --jre-home`
72 | fi
73 | fi
74 |
75 | if [ -z "$M2_HOME" ] ; then
76 | ## resolve links - $0 may be a link to maven's home
77 | PRG="$0"
78 |
79 | # need this for relative symlinks
80 | while [ -h "$PRG" ] ; do
81 | ls=`ls -ld "$PRG"`
82 | link=`expr "$ls" : '.*-> \(.*\)$'`
83 | if expr "$link" : '/.*' > /dev/null; then
84 | PRG="$link"
85 | else
86 | PRG="`dirname "$PRG"`/$link"
87 | fi
88 | done
89 |
90 | saveddir=`pwd`
91 |
92 | M2_HOME=`dirname "$PRG"`/..
93 |
94 | # make it fully qualified
95 | M2_HOME=`cd "$M2_HOME" && pwd`
96 |
97 | cd "$saveddir"
98 | # echo Using m2 at $M2_HOME
99 | fi
100 |
101 | # For Cygwin, ensure paths are in UNIX format before anything is touched
102 | if $cygwin ; then
103 | [ -n "$M2_HOME" ] &&
104 | M2_HOME=`cygpath --unix "$M2_HOME"`
105 | [ -n "$JAVA_HOME" ] &&
106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
107 | [ -n "$CLASSPATH" ] &&
108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
109 | fi
110 |
111 | # For Migwn, ensure paths are in UNIX format before anything is touched
112 | if $mingw ; then
113 | [ -n "$M2_HOME" ] &&
114 | M2_HOME="`(cd "$M2_HOME"; pwd)`"
115 | [ -n "$JAVA_HOME" ] &&
116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
117 | # TODO classpath?
118 | fi
119 |
120 | if [ -z "$JAVA_HOME" ]; then
121 | javaExecutable="`which javac`"
122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
123 | # readlink(1) is not available as standard on Solaris 10.
124 | readLink=`which readlink`
125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
126 | if $darwin ; then
127 | javaHome="`dirname \"$javaExecutable\"`"
128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
129 | else
130 | javaExecutable="`readlink -f \"$javaExecutable\"`"
131 | fi
132 | javaHome="`dirname \"$javaExecutable\"`"
133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
134 | JAVA_HOME="$javaHome"
135 | export JAVA_HOME
136 | fi
137 | fi
138 | fi
139 |
140 | if [ -z "$JAVACMD" ] ; then
141 | if [ -n "$JAVA_HOME" ] ; then
142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
143 | # IBM's JDK on AIX uses strange locations for the executables
144 | JAVACMD="$JAVA_HOME/jre/sh/java"
145 | else
146 | JAVACMD="$JAVA_HOME/bin/java"
147 | fi
148 | else
149 | JAVACMD="`which java`"
150 | fi
151 | fi
152 |
153 | if [ ! -x "$JAVACMD" ] ; then
154 | echo "Error: JAVA_HOME is not defined correctly." >&2
155 | echo " We cannot execute $JAVACMD" >&2
156 | exit 1
157 | fi
158 |
159 | if [ -z "$JAVA_HOME" ] ; then
160 | echo "Warning: JAVA_HOME environment variable is not set."
161 | fi
162 |
163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
164 |
165 | # traverses directory structure from process work directory to filesystem root
166 | # first directory with .mvn subdirectory is considered project base directory
167 | find_maven_basedir() {
168 |
169 | if [ -z "$1" ]
170 | then
171 | echo "Path not specified to find_maven_basedir"
172 | return 1
173 | fi
174 |
175 | basedir="$1"
176 | wdir="$1"
177 | while [ "$wdir" != '/' ] ; do
178 | if [ -d "$wdir"/.mvn ] ; then
179 | basedir=$wdir
180 | break
181 | fi
182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
183 | if [ -d "${wdir}" ]; then
184 | wdir=`cd "$wdir/.."; pwd`
185 | fi
186 | # end of workaround
187 | done
188 | echo "${basedir}"
189 | }
190 |
191 | # concatenates all lines of a file
192 | concat_lines() {
193 | if [ -f "$1" ]; then
194 | echo "$(tr -s '\n' ' ' < "$1")"
195 | fi
196 | }
197 |
198 | BASE_DIR=`find_maven_basedir "$(pwd)"`
199 | if [ -z "$BASE_DIR" ]; then
200 | exit 1;
201 | fi
202 |
203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
204 | echo $MAVEN_PROJECTBASEDIR
205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
206 |
207 | # For Cygwin, switch paths to Windows format before running java
208 | if $cygwin; then
209 | [ -n "$M2_HOME" ] &&
210 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
211 | [ -n "$JAVA_HOME" ] &&
212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
213 | [ -n "$CLASSPATH" ] &&
214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
215 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
217 | fi
218 |
219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
220 |
221 | exec "$JAVACMD" \
222 | $MAVEN_OPTS \
223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
226 |
--------------------------------------------------------------------------------
/README.adoc:
--------------------------------------------------------------------------------
1 | = Codility for Programmers:
2 |
3 |
4 |
5 | == https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/[Available Lessons]
6 |
7 |
8 | == https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/BinaryGap[Solutions to Lesson 1: Binary Gap]
9 |
10 | * https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/BinaryGap/BinaryGap.java[*Binary Gap:*] Find longest sequence of zeros in binary representation of an integer.
11 |
12 | A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
13 |
14 | For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.
15 |
16 | [source,java]
17 | -----------------
18 | Write a function:
19 |
20 | class Solution { public int solution(int N); }
21 | -----------------
22 |
23 |
24 | that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
25 |
26 | For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.
27 |
28 | Assume that:: N is an integer within the range [1..2,147,483,647].
29 |
30 | Complexity:
31 | expected worst-case time complexity is O(log(N));
32 | expected worst-case space complexity is O(1).
33 |
34 | == https://github.com/sunilsoni/Codility-Practice/tree/master/src/com/codility/lessons/Arrays[Solutions to Lesson 2: Arrays]
35 |
36 | * https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/Arrays/OddOccurrencesInArray.java[*Odd Occurrences In Array:*] Find value that occurs in odd number of elements.
37 |
38 | A non-empty zero-indexed array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
39 |
40 | For example, in array A such that:
41 | [source,java]
42 | -----------------
43 | A[0] = 9 A[1] = 3 A[2] = 9
44 | A[3] = 3 A[4] = 9 A[5] = 7
45 | A[6] = 9
46 | -----------------
47 | the elements at indexes 0 and 2 have value 9,
48 | the elements at indexes 1 and 3 have value 3,
49 | the elements at indexes 4 and 6 have value 9,
50 | the element at index 5 has value 7 and is unpaired.
51 | Write a function:
52 | [source,java]
53 | -----------------
54 | class Solution { public int solution(int[] A); }
55 | -----------------
56 | that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.
57 |
58 | For example, given array A such that:
59 | [source,java]
60 | -----------------
61 | A[0] = 9 A[1] = 3 A[2] = 9
62 | A[3] = 3 A[4] = 9 A[5] = 7
63 | A[6] = 9
64 | -----------------
65 | the function should return 7, as explained in the example above.
66 |
67 | Assume that::
68 |
69 | N is an odd integer within the range [1..1,000,000];
70 | each element of array A is an integer within the range [1..1,000,000,000];
71 | all but one of the values in A occur an even number of times.
72 | Complexity:
73 |
74 | expected worst-case time complexity is O(N);
75 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
76 |
77 |
78 | * https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/Arrays/CyclicRotation.java[*Cyclic Rotation:*] Rotate an array to the right by a given number of steps.
79 | A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).
80 |
81 | The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.
82 |
83 | Write a function:
84 | [source,java]
85 | -----------------
86 | class Solution { public int[] solution(int[] A, int K); }
87 | -----------------
88 |
89 | that, given a zero-indexed array A consisting of N integers and an integer K, returns the array A rotated K times.
90 |
91 | For example, given
92 | [source,java]
93 | -----------------
94 | A = [3, 8, 9, 7, 6]
95 | K = 3
96 | -----------------
97 | the function should return [9, 7, 6, 3, 8]. Three rotations were made:
98 |
99 |
100 | [source,java]
101 | -----------------
102 | [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
103 | [6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
104 | [7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
105 | -----------------
106 |
107 | [source,java]
108 | -----------------
109 | For another example, given
110 | A = [0, 0, 0]
111 | K = 1
112 | the function should return [0, 0, 0]
113 | -----------------
114 | Given:
115 | [source,java]
116 | -----------------
117 | A = [1, 2, 3, 4]
118 | K = 4
119 | the function should return [1, 2, 3, 4]
120 | -----------------
121 | Assume that::
122 |
123 | N and K are integers within the range [0..100];
124 | each element of array A is an integer within the range [−1,000..1,000].
125 | In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.
126 |
127 |
128 | == https://github.com/sunilsoni/Codility-Practice/tree/master/src/com/codility/lessons/TimeComplexity[Solutions to Lesson 3: Time Complexity]
129 |
130 | * https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/TimeComplexity/FrogJmp.java[*Frog Jump:*] Count minimal number of jumps from position X to Y.
131 | A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
132 |
133 | Count the minimal number of jumps that the small frog must perform to reach its target.
134 |
135 | Write a function:
136 | [source,java]
137 | -----------------
138 | class Solution { public int solution(int X, int Y, int D); }
139 | -----------------
140 | that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
141 |
142 | For example, given:
143 | [source,java]
144 | -----------------
145 | X = 10
146 | Y = 85
147 | D = 30
148 | -----------------
149 | the function should return 3, because the frog will be positioned as follows:
150 |
151 | after the first jump, at position 10 + 30 = 40
152 | after the second jump, at position 10 + 30 + 30 = 70
153 | after the third jump, at position 10 + 30 + 30 + 30 = 100
154 | Assume that::
155 |
156 | X, Y and D are integers within the range [1..1,000,000,000];
157 | X ≤ Y.
158 |
159 | Complexity:
160 |
161 | expected worst-case time complexity is O(1);
162 | expected worst-case space complexity is O(1).
163 |
164 | * https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/TimeComplexity/PermMissingElem.java[*Perm Missing Element:*] Find the missing element in a given permutation.
165 | A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
166 |
167 | Your goal is to find that missing element.
168 |
169 | Write a function:
170 | [source,java]
171 | -----------------
172 | class Solution { public int solution(int[] A); }
173 | -----------------
174 | that, given a zero-indexed array A, returns the value of the missing element.
175 |
176 | For example, given array A such that:
177 | [source,java]
178 | -----------------
179 | A[0] = 2
180 | A[1] = 3
181 | A[2] = 1
182 | A[3] = 5
183 | -----------------
184 | the function should return 4, as it is the missing element.
185 |
186 | Assume that::
187 |
188 | N is an integer within the range [0..100,000];
189 | the elements of A are all distinct;
190 | each element of array A is an integer within the range [1..(N + 1)].
191 | Complexity:
192 |
193 | expected worst-case time complexity is O(N);
194 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
195 |
196 |
197 | * https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/TimeComplexity/TapeEquilibrium.java[*Tape Equilibrium:*] Minimize the value |(A[0] + ... + A[P-1]) - (A[P] + ... + A[N-1])|.
198 |
199 | A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape.
200 |
201 | Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
202 |
203 | The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
204 |
205 | In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
206 |
207 | For example, consider array A such that:
208 | [source,java]
209 | -----------------
210 | A[0] = 3
211 | A[1] = 1
212 | A[2] = 2
213 | A[3] = 4
214 | A[4] = 3
215 | -----------------
216 | We can split this tape in four places:
217 | [source,java]
218 | -----------------
219 | P = 1, difference = |3 − 10| = 7
220 | P = 2, difference = |4 − 9| = 5
221 | P = 3, difference = |6 − 7| = 1
222 | P = 4, difference = |10 − 3| = 7
223 | -----------------
224 | Write a function:
225 | [source,java]
226 | -----------------
227 | class Solution { public int solution(int[] A); }
228 | -----------------
229 |
230 | that, given a non-empty zero-indexed array A of N integers, returns the minimal difference that can be achieved.
231 |
232 | For example, given:
233 | [source,java]
234 | -----------------
235 | A[0] = 3
236 | A[1] = 1
237 | A[2] = 2
238 | A[3] = 4
239 | A[4] = 3
240 | -----------------
241 | the function should return 1, as explained above.
242 |
243 | Assume that::
244 |
245 | N is an integer within the range [2..100,000];
246 | each element of array A is an integer within the range [−1,000..1,000].
247 | Complexity:
248 |
249 | expected worst-case time complexity is O(N);
250 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
251 |
252 |
253 |
254 | == https://github.com/sunilsoni/Codility-Practice/tree/master/src/com/codility/lessons/CountingElements[Solutions to Lesson 4: Counting Elements]
255 |
256 | * https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/CountingElements/PermutationCheck.java[*Permutation Check:*] Check whether array A is a permutation.
257 |
258 | A non-empty zero-indexed array A consisting of N integers is given.
259 |
260 | A permutation is a sequence containing each element from 1 to N once, and only once.
261 |
262 | For example, array A such that:
263 | [source,java]
264 | -----------------
265 | A[0] = 4
266 | A[1] = 1
267 | A[2] = 3
268 | A[3] = 2
269 | -----------------
270 | is a permutation, but array A such that:
271 | [source,java]
272 | -----------------
273 | A[0] = 4
274 | A[1] = 1
275 | A[2] = 3
276 | -----------------
277 | is not a permutation, because value 2 is missing.
278 |
279 | The goal is to check whether array A is a permutation.
280 |
281 | Write a function:
282 | [source,java]
283 | -----------------
284 | class Solution { public int solution(int[] A); }
285 | -----------------
286 |
287 | that, given a zero-indexed array A, returns 1 if array A is a permutation and 0 if it is not.
288 |
289 | For example, given array A such that:
290 | [source,java]
291 | -----------------
292 | A[0] = 4
293 | A[1] = 1
294 | A[2] = 3
295 | A[3] = 2
296 | -----------------
297 | the function should return 1.
298 |
299 | Given array A such that:
300 | [source,java]
301 | -----------------
302 | A[0] = 4
303 | A[1] = 1
304 | A[2] = 3
305 | -----------------
306 | the function should return 0.
307 |
308 | Assume that::
309 |
310 | N is an integer within the range [1..100,000];
311 | each element of array A is an integer within the range [1..1,000,000,000].
312 | Complexity:
313 |
314 | expected worst-case time complexity is O(N);
315 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
316 |
317 |
318 |
319 | == https://github.com/sunilsoni/Codility-Practice/tree/master/src/main/java/com/codility/lessons/Sorting[Solutions to Lesson 6: Sorting]
320 |
321 | * https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/Sorting/Distinct.java[*Distinct:*] Compute number of distinct values in an array.
322 |
323 |
324 | Write a function
325 |
326 | [source,java]
327 | -----------------
328 | class Solution { public int solution(int[] A); }
329 | -----------------
330 |
331 | that, given a zero-indexed array A consisting of N integers, returns the number of distinct values in array A.
332 |
333 | Assume that::
334 |
335 | N is an integer within the range [0..100,000];
336 | each element of array A is an integer within the range [−1,000,000..1,000,000].
337 | For example, given array A consisting of six elements such that:
338 | [source,java]
339 | -----------------
340 | A[0] = 2 A[1] = 1 A[2] = 1
341 | A[3] = 2 A[4] = 3 A[5] = 1
342 | -----------------
343 | the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.
344 |
345 | Complexity:
346 |
347 | expected worst-case time complexity is O(N*log(N));
348 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
349 |
350 |
351 | * https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/Sorting/Triangle.java[*Triangle:*] Determine whether a triangle can be built from a given set of edges.
352 |
353 | A zero-indexed array A consisting of N integers is given. A triplet (P, Q, R) is triangular if 0 ≤ P < Q < R < N and:
354 | [source,java]
355 | -----------------
356 | A[P] + A[Q] > A[R],
357 | A[Q] + A[R] > A[P],
358 | A[R] + A[P] > A[Q].
359 | -----------------
360 | For example, consider array A such that:
361 | [source,java]
362 | -----------------
363 | A[0] = 10 A[1] = 2 A[2] = 5
364 | A[3] = 1 A[4] = 8 A[5] = 20
365 | -----------------
366 | Triplet (0, 2, 4) is triangular.
367 |
368 | Write a function:
369 | [source,java]
370 | -----------------
371 | class Solution { public int solution(int[] A); }
372 | -----------------
373 |
374 | that, given a zero-indexed array A consisting of N integers, returns 1 if there exists a triangular triplet for this array and returns 0 otherwise.
375 |
376 | For example, given array A such that:
377 | [source,java]
378 | -----------------
379 | A[0] = 10 A[1] = 2 A[2] = 5
380 | A[3] = 1 A[4] = 8 A[5] = 20
381 | -----------------
382 | the function should return 1, as explained above. Given array A such that:
383 | [source,java]
384 | -----------------
385 | A[0] = 10 A[1] = 50 A[2] = 5
386 | A[3] = 1
387 | -----------------
388 | the function should return 0.
389 |
390 | Assume that::
391 |
392 | N is an integer within the range [0..100,000];
393 | each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
394 | Complexity:
395 |
396 | expected worst-case time complexity is O(N*log(N));
397 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
398 |
399 |
400 | * https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/Sorting/MaxProductOfThree.java[*MaxProductOfThree:*] Maximize A[P] * A[Q] * A[R] for any triplet (P, Q, R).
401 |
402 | A non-empty zero-indexed array A consisting of N integers is given. The product of triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N).
403 |
404 | For example, array A such that:
405 | [source,java]
406 | -----------------
407 | A[0] = -3
408 | A[1] = 1
409 | A[2] = 2
410 | A[3] = -2
411 | A[4] = 5
412 | A[5] = 6
413 | -----------------
414 | contains the following example triplets:
415 | [source,java]
416 | -----------------
417 | (0, 1, 2), product is −3 * 1 * 2 = −6
418 | (1, 2, 4), product is 1 * 2 * 5 = 10
419 | (2, 4, 5), product is 2 * 5 * 6 = 60
420 | -----------------
421 | Your goal is to find the maximal product of any triplet.
422 |
423 | Write a function:
424 | [source,java]
425 | -----------------
426 | class Solution { public int solution(int[] A); }
427 | -----------------
428 |
429 | that, given a non-empty zero-indexed array A, returns the value of the maximal product of any triplet.
430 |
431 | For example, given array A such that:
432 | [source,java]
433 | -----------------
434 | A[0] = -3
435 | A[1] = 1
436 | A[2] = 2
437 | A[3] = -2
438 | A[4] = 5
439 | A[5] = 6
440 | -----------------
441 | the function should return 60, as the product of triplet (2, 4, 5) is maximal.
442 |
443 | Assume that::
444 |
445 | N is an integer within the range [3..100,000];
446 | each element of array A is an integer within the range [−1,000..1,000].
447 | Complexity:
448 |
449 | expected worst-case time complexity is O(N*log(N));
450 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
451 |
452 |
453 | * https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/Sorting/NumberOfDiscIntersections.java[*Number Of Disc Intersections:*] Compute the number of intersections in a sequence of discs.
454 |
455 | We draw N discs on a plane. The discs are numbered from 0 to N − 1. A zero-indexed array A of N non-negative integers, specifying the radiuses of the discs, is given. The J-th disc is drawn with its center at (J, 0) and radius A[J].
456 |
457 | We say that the J-th disc and K-th disc intersect if J ≠ K and the J-th and K-th discs have at least one common point (assuming that the discs contain their borders).
458 |
459 | The figure below shows discs drawn for N = 6 and A as follows:
460 | [source,java]
461 | -----------------
462 | A[0] = 1
463 | A[1] = 5
464 | A[2] = 2
465 | A[3] = 1
466 | A[4] = 4
467 | A[5] = 0
468 | -----------------
469 |
470 | There are eleven (unordered) pairs of discs that intersect, namely:
471 |
472 | discs 1 and 4 intersect, and both intersect with all the other discs;
473 | disc 2 also intersects with discs 0 and 3.
474 | Write a function:
475 | [source,java]
476 | -----------------
477 | class Solution { public int solution(int[] A); }
478 | -----------------
479 |
480 | that, given an array A describing N discs as explained above, returns the number of (unordered) pairs of intersecting discs. The function should return −1 if the number of intersecting pairs exceeds 10,000,000.
481 |
482 | Given array A shown above, the function should return 11, as explained above.
483 |
484 | Assume that::
485 |
486 | N is an integer within the range [0..100,000];
487 | each element of array A is an integer within the range [0..2,147,483,647].
488 | Complexity:
489 |
490 | expected worst-case time complexity is O(N*log(N));
491 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
492 |
493 |
494 |
495 | == https://github.com/sunilsoni/Codility-Practice/tree/master/src/main/java/com/codility/lessons/StacksQueues[Solutions to Lesson 7: Stacks and Queues]
496 |
497 | * https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/StacksQueues/Brackets.java[*Brackets:*] Determine whether a given string of parentheses (multiple types) is properly nested.
498 |
499 | A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:
500 |
501 | S is empty;
502 | S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
503 | S has the form "VW" where V and W are properly nested strings.
504 | For example, the string "{[()()]}" is properly nested but "([)()]" is not.
505 |
506 | Write a function:
507 |
508 | [source,java]
509 | -----------------
510 | class Solution { public int solution(String S); }
511 | -----------------
512 |
513 | that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.
514 |
515 | For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above.
516 |
517 | Assume that::
518 |
519 | N is an integer within the range [0..200,000];
520 | string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".
521 |
522 | Complexity::
523 |
524 | expected worst-case time complexity is O(N);
525 | expected worst-case space complexity is O(N) (not counting the storage required for input arguments).
526 |
527 |
528 | * https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/StacksQueues/Nesting.java[*Nesting:*] Determine whether a given string of parentheses (single type) is properly nested.
529 |
530 | A string S consisting of N characters is called properly nested if:
531 |
532 | S is empty;
533 | S has the form "(U)" where U is a properly nested string;
534 | S has the form "VW" where V and W are properly nested strings.
535 | For example, string "(()(())())" is properly nested but string "())" isn't.
536 |
537 | Write a function:
538 | [source,java]
539 | -----------------
540 | class Solution { public int solution(String S); }
541 | -----------------
542 |
543 | that, given a string S consisting of N characters, returns 1 if string S is properly nested and 0 otherwise.
544 |
545 | For example, given S = "(()(())())", the function should return 1 and given S = "())", the function should return 0, as explained above.
546 |
547 | Assume that::
548 |
549 | N is an integer within the range [0..1,000,000];
550 | string S consists only of the characters "(" and/or ")".
551 |
552 | Complexity::
553 |
554 | expected worst-case time complexity is O(N);
555 | expected worst-case space complexity is O(1) (not counting the storage required for input arguments).
556 |
557 |
558 | * https://github.com/sunilsoni/Codility-Practice/blob/master/src/main/java/com/codility/lessons/StacksQueues/StoneWall.java[*StoneWall:*] Cover "Manhattan skyline" using the minimum number of rectangles.
559 |
560 | You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by an array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end.
561 |
562 | The wall should be built of cuboid stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall.
563 |
564 | Write a function:
565 |
566 | [source,java]
567 | -----------------
568 | class Solution { public int solution(int[] H); }
569 | -----------------
570 |
571 | that, given an array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it.
572 |
573 | For example, given array H containing N = 9 integers:
574 | [source,java]
575 | -----------------
576 | H[0] = 8 H[1] = 8 H[2] = 5
577 | H[3] = 7 H[4] = 9 H[5] = 8
578 | H[6] = 7 H[7] = 4 H[8] = 8
579 | -----------------
580 | the function should return 7. The figure shows one possible arrangement of seven blocks.
581 |
582 |
583 |
584 | Assume that::
585 |
586 | N is an integer within the range [1..100,000];
587 | each element of array H is an integer within the range [1..1,000,000,000].
588 |
589 | Complexity::
590 |
591 | expected worst-case time complexity is O(N);
592 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
593 |
--------------------------------------------------------------------------------