├── .classpath
├── .gitignore
├── README.md
└── src
├── binarysearch
├── MinMaxDivision.java
└── NailingPlanks.java
├── caterpillar
├── AbsDistinct.java
├── CountDistinctSlices.java
├── CountTriangles.java
└── MinAbsSumOfTwo.java
├── countingelements
├── FrogRiverOne.java
├── MaxCounter.java
├── MissingInteger.java
└── PermCheck.java
├── euclideanalgorithm
├── ChocoladeByNumbers.java
└── CommonPrimeDivisors.java
├── fibonaccinumbers
├── FibFrog.java
└── Ladder.java
├── greedyalgorithms
└── TieRope.java
├── leader
├── Dominator.java
└── EquiLeader.java
├── maximumslice
├── MaxDoubleSliceSum.java
├── MaxProfit.java
└── MaxSliceSum.java
├── prefixsums
├── CountDiv.java
├── GenomicRangeQuery.java
├── MinAvgTwoSlice.java
└── PassingCars.java
├── primeandcompositenumbers
├── CountFactors.java
├── Flags.java
├── MinPerimeterRectangle.java
└── Peaks.java
├── sieveoferastothenes
├── CountNonDivisible.java
└── CountSemiprimes.java
├── sorting
├── Distinct.java
├── MaxProductOfThree.java
├── NumberOfDiscIntersection.java
└── Triangle.java
├── stackandqueue
├── Brackets.java
├── Fish.java
├── Nesting.java
└── StoneWall.java
└── timecomplexity
├── FrogJump.java
├── PermMissingElements.java
└── TapeEquilibrium.java
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .settings
2 | bin
3 | .project
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Java Codility Solutions
2 | =======================
3 |
4 | Codility lessons solved in Java:
5 |
6 | - Time Complexity
7 | - TapeEquilibrium
8 | - FrogJmp
9 | - PermMissingElem
10 | - Counting Elements
11 | - PermCheck
12 | - FrogRiverOne
13 | - MissingInteger
14 | - MaxCounters
15 | - Prefix Sums
16 | - PassingCars
17 | - CountDiv
18 | - MinAvgTwoSlice
19 | - GenomicRangeQuery
20 | - Sorting
21 | - MaxProductOfThree
22 | - Triangle
23 | - Distinct
24 | - NumberOfDiscIntersections
25 | - Stacks and Queues
26 | - Brackets
27 | - Nesting
28 | - StoneWall
29 | - Fish
30 | - Leader
31 | - Dominator
32 | - EquiLeader
33 | - Maximum slice problem
34 | - MaxProfit
35 | - MaxDoubleSliceSum
36 | - MaxSliceSum
37 | - Prime and composite numbers
38 | - CountFactors
39 | - MinPerimeterRectangle
40 | - Peaks
41 | - Flags
42 | - Sieve of Erastothenes
43 | - CountSemiprimes
44 | - CountNonDivisible
45 | - Euclidian algorithm
46 | - ChocolatesByNumbers
47 | - CommonPrimeDivisors
48 | - Fibonacci numbers
49 | - Ladder
50 | - FibFrog
51 | - Binary search algorithm
52 | - MinMaxDivision
53 | - NailingPlanks
54 | - Caterpillar method
55 | - AbsDistinct
56 | - CountTriangles
57 | - CountDistinctSlices
58 | - MinAbsSumOfTwo
59 | - Greedy algorithms
60 | - TieRopes
61 |
62 |
--------------------------------------------------------------------------------
/src/binarysearch/MinMaxDivision.java:
--------------------------------------------------------------------------------
1 | /*
2 | You are given integers K, M and a non-empty zero-indexed array A consisting of N integers. Every element of the array is not greater than M.
3 | You should divide this array into K blocks of consecutive elements. The size of the block is any integer between 0 and N. Every element of the array should belong to some block.
4 | The sum of the block from X to Y equals A[X] + A[X + 1] + ... + A[Y]. The sum of empty block equals 0.
5 | The large sum is the maximal sum of any block.
6 | For example, you are given integers K = 3, M = 5 and array A such that:
7 | A[0] = 2
8 | A[1] = 1
9 | A[2] = 5
10 | A[3] = 1
11 | A[4] = 2
12 | A[5] = 2
13 | A[6] = 2
14 | The array can be divided, for example, into the following blocks:
15 | [2, 1, 5, 1, 2, 2, 2], [], [] with a large sum of 15;
16 | [2], [1, 5, 1, 2], [2, 2] with a large sum of 9;
17 | [2, 1, 5], [], [1, 2, 2, 2] with a large sum of 8;
18 | [2, 1], [5, 1], [2, 2, 2] with a large sum of 6.
19 | The goal is to minimize the large sum. In the above example, 6 is the minimal large sum.
20 | Write a function:
21 | class Solution { public int solution(int K, int M, int[] A); }
22 | that, given integers K, M and a non-empty zero-indexed array A consisting of N integers, returns the minimal large sum.
23 | For example, given K = 3, M = 5 and array A such that:
24 | A[0] = 2
25 | A[1] = 1
26 | A[2] = 5
27 | A[3] = 1
28 | A[4] = 2
29 | A[5] = 2
30 | A[6] = 2
31 | the function should return 6, as explained above. Assume that:
32 | N and K are integers within the range [1..100,000];
33 | M is an integer within the range [0..10,000];
34 | each element of array A is an integer within the range [0..M].
35 | Complexity:
36 | expected worst-case time complexity is O(N*log(N+M));
37 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
38 | Elements of input arrays can be modified.
39 | */
40 |
41 | //SCORE: 100/100 (both, recursive and iterative approach)
42 | package binarysearch;
43 |
44 | public class MinMaxDivision {
45 |
46 | public static void main(String[] args) {
47 | int[] A = new int[]{2,1,5,1,2,2,2};
48 | int M = 5;
49 | int K = 3;
50 | System.out.println(solution(K, M, A));
51 | }
52 |
53 | public static int solution(int K, int M, int[] A) {
54 | int sum=0;
55 | int largestEl = 0;
56 | for (int i = 0; i < A.length; i++) {
57 | largestEl= largestEl>=A[i] ? largestEl:A[i];
58 | sum += A[i];
59 | }
60 | int idealMin = Math.max((int)Math.ceil((double)sum/K), largestEl);
61 | return binarySearchIterative(idealMin, sum, A, K);
62 | }
63 |
64 | public static int binarySearchRecursive(int min, int max, int[] A, int K) {
65 | if (max - min < 2)
66 | if (verifySolution(min, A, K))
67 | return min;
68 | else
69 | return max;
70 | int middle = (min+max)/2;
71 | if (verifySolution(middle, A, K))
72 | return binarySearchRecursive(min, middle, A, K);
73 | else
74 | return binarySearchRecursive(middle, max, A, K);
75 | }
76 |
77 | public static int binarySearchIterative(int min, int max, int[] A, int K) {
78 | int res=0;
79 | int beg= min;
80 | int end = max;
81 | while (beg<=end) {
82 | int middle = (beg+end)/2;
83 | if (verifySolution(middle,A,K)) {
84 | end=middle-1;
85 | res = middle;
86 | } else
87 | beg=middle+1;
88 | }
89 | return res;
90 | }
91 |
92 | public static boolean verifySolution(int x, int[] A, int K) {
93 | int tmp=0;
94 | int count=1;
95 | for (int i = 0; i < A.length; i++) {
96 | if (tmp + A[i] <= x)
97 | tmp += A[i];
98 | else{
99 | count++;
100 | tmp=A[i];
101 | if (count>K)
102 | return false;
103 | }
104 | }
105 | return true;
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/src/binarysearch/NailingPlanks.java:
--------------------------------------------------------------------------------
1 | /*
2 | You are given two non-empty zero-indexed arrays A and B consisting of N integers. These arrays represent N planks. More precisely, A[K] is the start and B[K] the end of the K−th plank.
3 | Next, you are given a non-empty zero-indexed array C consisting of M integers. This array represents M nails. More precisely, C[I] is the position where you can hammer in the I−th nail.
4 | We say that a plank (A[K], B[K]) is nailed if there exists a nail C[I] such that A[K] ≤ C[I] ≤ B[K].
5 | The goal is to find the minimum number of nails that must be used until all the planks are nailed. In other words, you should find a value J such that all planks will be nailed after using only the first J nails. More precisely, for every plank (A[K], B[K]) such that 0 ≤ K < N, there should exist a nail C[I] such that I < J and A[K] ≤ C[I] ≤ B[K].
6 | For example, given arrays A, B such that:
7 | A[0] = 1 B[0] = 4
8 | A[1] = 4 B[1] = 5
9 | A[2] = 5 B[2] = 9
10 | A[3] = 8 B[3] = 10
11 | four planks are represented: [1, 4], [4, 5], [5, 9] and [8, 10].
12 | Given array C such that:
13 | C[0] = 4
14 | C[1] = 6
15 | C[2] = 7
16 | C[3] = 10
17 | C[4] = 2
18 | if we use the following nails:
19 | 0, then planks [1, 4] and [4, 5] will both be nailed.
20 | 0, 1, then planks [1, 4], [4, 5] and [5, 9] will be nailed.
21 | 0, 1, 2, then planks [1, 4], [4, 5] and [5, 9] will be nailed.
22 | 0, 1, 2, 3, then all the planks will be nailed.
23 | Thus, four is the minimum number of nails that, used sequentially, allow all the planks to be nailed.
24 | Write a function:
25 | class Solution { public int solution(int[] A, int[] B, int[] C); }
26 | that, given two non-empty zero-indexed arrays A and B consisting of N integers and a non-empty zero-indexed array C consisting of M integers, returns the minimum number of nails that, used sequentially, allow all the planks to be nailed.
27 | If it is not possible to nail all the planks, the function should return −1.
28 | For example, given arrays A, B, C such that:
29 | A[0] = 1 B[0] = 4
30 | A[1] = 4 B[1] = 5
31 | A[2] = 5 B[2] = 9
32 | A[3] = 8 B[3] = 10
33 |
34 | C[0] = 4
35 | C[1] = 6
36 | C[2] = 7
37 | C[3] = 10
38 | C[4] = 2
39 | the function should return 4, as explained above.
40 | Assume that:
41 | N and M are integers within the range [1..30,000];
42 | each element of arrays A, B, C is an integer within the range [1..2*M];
43 | A[K] ≤ B[K].
44 | Complexity:
45 | expected worst-case time complexity is O((N+M)*log(M));
46 | expected worst-case space complexity is O(M), beyond input storage (not counting the storage required for input arguments).
47 | Elements of input arrays can be modified.
48 | */
49 |
50 | //SCORE: 100/100
51 | package binarysearch;
52 |
53 | import java.util.Arrays;
54 |
55 | public class NailingPlanks {
56 |
57 | public static void main(String[] args) {
58 | int[] A = new int[]{1,4,5,8};
59 | int[] B = new int[]{4,5,9,10};
60 | int[] C = new int[]{4,6,7,10,2};
61 |
62 |
63 | System.out.println(solution(A, B, C));
64 | }
65 |
66 | public static int solution(int[] A, int[] B, int[] C) {
67 | int N = A.length;
68 | int M = C.length;
69 | int[][] sortedNails = new int[M][2];
70 | for (int i = 0; i < M; i++) {
71 | sortedNails[i][0] = C[i];
72 | sortedNails[i][1] = i;
73 | }
74 | Arrays.sort(sortedNails, (int[] x, int[] y) -> (Integer.compare(x[0], y[0])));
75 |
76 | int res = 0;
77 | for (int i = 0; i < N; i++) {
78 | res = minIndex(A[i], B[i], sortedNails, res);
79 | if (res == -1)
80 | return -1;
81 | }
82 | return res+1;
83 | }
84 |
85 | public static int minIndex(int pStart, int pEnd, int[][] nails, int oldRes) {
86 | int beg = 0;
87 | int end = nails.length-1;
88 | int res=-1;
89 | while(beg<=end) {
90 | int middle= (beg + end) / 2;
91 | if (nails[middle][0] < pStart) {
92 | beg = middle+1;
93 |
94 | }else if(nails[middle][0] >pEnd) {
95 | end = middle -1;
96 | }
97 | else {
98 | end = middle-1;
99 | res = middle;
100 | }
101 | }
102 | if (res == -1 || nails[res][0] > pEnd)
103 | return -1;
104 | int min= nails[res][1];
105 | while(res < nails.length && nails[res][0] <= pEnd) {
106 | min = Math.min(min, nails[res][1]);
107 | if(min<=oldRes)
108 | return oldRes;
109 | res++;
110 | }
111 |
112 | return min;
113 | }
114 |
115 | }
116 |
--------------------------------------------------------------------------------
/src/caterpillar/AbsDistinct.java:
--------------------------------------------------------------------------------
1 | /*
2 | A non-empty zero-indexed array A consisting of N numbers is given. The array is sorted in non-decreasing order. The absolute distinct count of this array is the number of distinct absolute values among the elements of the array.
3 | For example, consider array A such that:
4 | A[0] = -5
5 | A[1] = -3
6 | A[2] = -1
7 | A[3] = 0
8 | A[4] = 3
9 | A[5] = 6
10 | The absolute distinct count of this array is 5, because there are 5 distinct absolute values among the elements of this array, namely 0, 1, 3, 5 and 6.
11 | Write a function:
12 | class Solution { public int solution(int[] A); }
13 | that, given a non-empty zero-indexed array A consisting of N numbers, returns absolute distinct count of array A.
14 | For example, given array A such that:
15 | A[0] = -5
16 | A[1] = -3
17 | A[2] = -1
18 | A[3] = 0
19 | A[4] = 3
20 | A[5] = 6
21 | the function should return 5, as explained above.
22 | Assume that:
23 | N is an integer within the range [1..100,000];
24 | each element of array A is an integer within the range [−2,147,483,648..2,147,483,647];
25 | array A is sorted in non-decreasing order.
26 | Complexity:
27 | expected worst-case time complexity is O(N);
28 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
29 | Elements of input arrays can be modified.
30 | */
31 |
32 | //SCORE: 100/100 (both solutions)
33 | package caterpillar;
34 |
35 | import java.util.Arrays;
36 | import java.util.stream.IntStream;
37 |
38 | public class AbsDistinct {
39 |
40 | public static void main(String[] args) {
41 | int[] A = new int[]{-5,-3,-1,0,3,6};
42 | System.out.println(solution(A));
43 | }
44 |
45 | //using Java 8
46 | public static int solution(int[] A) {
47 | return (int)IntStream.of(A).map(i->Math.abs(i)).distinct().count();
48 | }
49 |
50 | public static int solution1(int[] A) {
51 | int dupls = 0;
52 | for (int i = 0; i < A.length; i++) {
53 | if(A[i]<0)
54 | A[i] = -A[i];
55 | }
56 | Arrays.sort(A);
57 | for (int i = 1; i < A.length; i++) {
58 | if(A[i] == A[i-1])
59 | dupls++;
60 | }
61 | return A.length-dupls;
62 | }
63 |
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/src/caterpillar/CountDistinctSlices.java:
--------------------------------------------------------------------------------
1 | /*
2 | An integer M and a non-empty zero-indexed array A consisting of N non-negative integers are given. All integers in array A are less than or equal to M.
3 | A pair of integers (P, Q), such that 0 ≤ P ≤ Q < N, is called a slice of array A. The slice consists of the elements A[P], A[P + 1], ..., A[Q]. A distinct slice is a slice consisting of only unique numbers. That is, no individual number occurs more than once in the slice.
4 | For example, consider integer M = 6 and array A such that:
5 | A[0] = 3
6 | A[1] = 4
7 | A[2] = 5
8 | A[3] = 5
9 | A[4] = 2
10 | There are exactly nine distinct slices: (0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2), (3, 3), (3, 4) and (4, 4).
11 | The goal is to calculate the number of distinct slices.
12 | Write a function:
13 | class Solution { public int solution(int M, int[] A); }
14 | that, given an integer M and a non-empty zero-indexed array A consisting of N integers, returns the number of distinct slices.
15 | If the number of distinct slices is greater than 1,000,000,000, the function should return 1,000,000,000.
16 | For example, given integer M = 6 and array A such that:
17 | A[0] = 3
18 | A[1] = 4
19 | A[2] = 5
20 | A[3] = 5
21 | A[4] = 2
22 | the function should return 9, as explained above.
23 | Assume that:
24 | N is an integer within the range [1..100,000];
25 | M is an integer within the range [0..100,000];
26 | each element of array A is an integer within the range [0..M].
27 | Complexity:
28 | expected worst-case time complexity is O(N);
29 | expected worst-case space complexity is O(M), beyond input storage (not counting the storage required for input arguments).
30 | Elements of input arrays can be modified.
31 | */
32 |
33 | //SCORE: 100/100
34 | package caterpillar;
35 |
36 | public class CountDistinctSlices {
37 |
38 | public static void main(String[] args) {
39 | int[] A = new int[]{3, 4, 5, 5, 2};
40 | int M = 6;
41 | System.out.println(solution(A, M));
42 | }
43 |
44 | public static int solution(int[] A, int M) {
45 | return caterpillarMethod(A, M);
46 |
47 | }
48 |
49 | public static int caterpillarMethod(int[] A, int M) {
50 | int res = 0;
51 | int front = 0;
52 | int back =0;
53 | boolean[] seen = new boolean [M+1];
54 | while(front A[R],
4 | A[Q] + A[R] > A[P],
5 | A[R] + A[P] > A[Q].
6 | For example, consider array A such that:
7 | A[0] = 10 A[1] = 2 A[2] = 5
8 | A[3] = 1 A[4] = 8 A[5] = 12
9 | There are four triangular triplets that can be constructed from elements of this array, namely (0, 2, 4), (0, 2, 5), (0, 4, 5), and (2, 4, 5).
10 | Write a function:
11 | class Solution { public int solution(int[] A); }
12 | that, given a zero-indexed array A consisting of N integers, returns the number of triangular triplets in this array.
13 | For example, given array A such that:
14 | A[0] = 10 A[1] = 2 A[2] = 5
15 | A[3] = 1 A[4] = 8 A[5] = 12
16 | the function should return 4, as explained above.
17 | Assume that:
18 | N is an integer within the range [0..1,000];
19 | each element of array A is an integer within the range [1..1,000,000,000].
20 | Complexity:
21 | expected worst-case time complexity is O(N2);
22 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
23 | Elements of input arrays can be modified.
24 | */
25 |
26 | //SCORE: 100/100
27 | package caterpillar;
28 |
29 | import java.util.Arrays;
30 |
31 | public class CountTriangles {
32 |
33 | public static void main(String[] args) {
34 | int[] A = new int[] {10, 2, 5, 1, 8, 12};
35 | System.out.println(solution(A));
36 | }
37 |
38 | public static int solution(int[] A) {
39 | return caterpillarMethod(A);
40 | }
41 |
42 | public static int caterpillarMethod(int[] A) {
43 | int N = A.length;
44 | int res=0;
45 | if (N < 3)
46 | return 0;
47 | int front;
48 | Arrays.sort(A);
49 | for (int i = 0; i < N-2; i++) {
50 | front = i+2;
51 | for (int j = i+1; j < N-1; j++) {
52 | while(front < N && A[i] + A[j] > A[front]){
53 | front++;
54 | }
55 | res+=front-j-1;
56 | }
57 | }
58 | return res;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/caterpillar/MinAbsSumOfTwo.java:
--------------------------------------------------------------------------------
1 | /*
2 | Let A be a non-empty zero-indexed array consisting of N integers.
3 | The abs sum of two for a pair of indices (P, Q) is the absolute value |A[P] + A[Q]|, for 0 ≤ P ≤ Q < N.
4 | For example, the following array A:
5 | A[0] = 1
6 | A[1] = 4
7 | A[2] = -3
8 | has pairs of indices (0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2).
9 | The abs sum of two for the pair (0, 0) is A[0] + A[0] = |1 + 1| = 2.
10 | The abs sum of two for the pair (0, 1) is A[0] + A[1] = |1 + 4| = 5.
11 | The abs sum of two for the pair (0, 2) is A[0] + A[2] = |1 + (−3)| = 2.
12 | The abs sum of two for the pair (1, 1) is A[1] + A[1] = |4 + 4| = 8.
13 | The abs sum of two for the pair (1, 2) is A[1] + A[2] = |4 + (−3)| = 1.
14 | The abs sum of two for the pair (2, 2) is A[2] + A[2] = |(−3) + (−3)| = 6.
15 | Write a function:
16 | int solution(int A[], int N);
17 | that, given a non-empty zero-indexed array A consisting of N integers, returns the minimal abs sum of two for any pair of indices in this array.
18 | For example, given the following array A:
19 | A[0] = 1
20 | A[1] = 4
21 | A[2] = -3
22 | the function should return 1, as explained above.
23 | Given array A:
24 | A[0] = -8
25 | A[1] = 4
26 | A[2] = 5
27 | A[3] =-10
28 | A[4] = 3
29 | the function should return |(−8) + 5| = 3.
30 | Assume that:
31 | N is an integer within the range [1..100,000];
32 | each element of array A is an integer within the range [−1,000,000,000..1,000,000,000].
33 | Complexity:
34 | expected worst-case time complexity is O(N*log(N));
35 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
36 | Elements of input arrays can be modified.
37 | */
38 |
39 | //SCORE: 100/100 (both solutions, caterpillar and binary search)
40 | package caterpillar;
41 |
42 | import java.util.Arrays;
43 |
44 | public class MinAbsSumOfTwo {
45 |
46 | public static void main(String[] args) {
47 | int[] A = new int[]{1, 4, -3};
48 | System.out.println(solution1(A));
49 | }
50 |
51 | public static int solution(int[] A) {
52 | Arrays.sort(A);
53 | int min = Integer.MAX_VALUE;
54 | for (int i = 0; i < A.length; i++) {
55 | min = Math.min(min, Math.abs(A[i] + findBestMatch(-A[i],A)));
56 | }
57 | return min;
58 | }
59 |
60 | public static int solution1(int[] A) {
61 | Arrays.sort(A);
62 | return getMinSum(A);
63 | }
64 |
65 | public static int findBestMatch(int target, int[] A) {
66 | if (A.length == 1)
67 | return A[0];
68 | int beg = 0;
69 | int end = A.length - 1;
70 | while(beg<=end) {
71 | int middle= (beg+end)/2;
72 | if (A[middle] == target)
73 | return A[middle];
74 | if (end - beg == 1)
75 | return Math.abs(A[end] - target) < Math.abs(A[beg] - target)? A[end]: A[beg];
76 | if (A[middle]>target){
77 | end= middle;
78 | }else {
79 | beg = middle;
80 | }
81 | }
82 | return A[0];
83 | }
84 |
85 | public static int getMinSum(int[] A) {
86 | //all positives
87 | if (A[0]>=0)
88 | return A[0]*2;
89 | //all negatives
90 | if (A[A.length-1] <= 0)
91 | return -A[A.length-1]*2;
92 | int front = A.length - 1;
93 | int back = 0;
94 | int min = Math.abs(A[back] + A[front]);
95 | while (back<=front) {
96 | int tmp = Math.abs(A[back] + A[front]);
97 | min = Math.min(min,tmp);
98 | if (Math.abs(A[back+1] + A[front]) <= tmp)
99 | back++;
100 | else if(Math.abs(A[back] + A[front-1]) <= tmp)
101 | front--;
102 | else {
103 | back++;
104 | front--;
105 | }
106 | }
107 | return min;
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/src/countingelements/FrogRiverOne.java:
--------------------------------------------------------------------------------
1 | /*
2 | A non-empty zero-indexed array A consisting of N integers is given.
3 | A permutation is a sequence containing each element from 1 to N once, and only once.
4 | For example, array A such that:
5 | A[0] = 4
6 | A[1] = 1
7 | A[2] = 3
8 | A[3] = 2
9 | is a permutation, but array A such that:
10 | A[0] = 4
11 | A[1] = 1
12 | A[2] = 3
13 | is not a permutation, because value 2 is missing.
14 | The goal is to check whether array A is a permutation.
15 | Write a function:
16 | class Solution { public int solution(int[] A); }
17 | that, given a zero-indexed array A, returns 1 if array A is a permutation and 0 if it is not.
18 | For example, given array A such that:
19 | A[0] = 4
20 | A[1] = 1
21 | A[2] = 3
22 | A[3] = 2
23 | the function should return 1.
24 | Given array A such that:
25 | A[0] = 4
26 | A[1] = 1
27 | A[2] = 3
28 | the function should return 0.
29 | Assume that:
30 | N is an integer within the range [1..100,000];
31 | each element of array A is an integer within the range [1..1,000,000,000].
32 | Complexity:
33 | expected worst-case time complexity is O(N);
34 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
35 | Elements of input arrays can be modified.
36 | */
37 |
38 | //SCORE: 100/100
39 | package countingelements;
40 |
41 | public class FrogRiverOne {
42 |
43 | public static void main(String[] args) {
44 | int[] A = new int[]{1,3,1,4,2,3,5,4};
45 | int X = 5;
46 | System.out.println(solution(A,X));
47 | }
48 | public static int solution(int[] A, int X) {
49 | int tmp = 0;
50 | boolean[] hasLeaf = new boolean[X+1];
51 | for (int i = 0; i < A.length; i++) {
52 | if (!hasLeaf[A[i]] && A[i]<=X) {
53 | hasLeaf[A[i]] = true;
54 | tmp++;
55 | }
56 | if (tmp ==X)
57 | return i;
58 | }
59 | return -1;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/countingelements/MaxCounter.java:
--------------------------------------------------------------------------------
1 | /*
2 | You are given N counters, initially set to 0, and you have two possible operations on them:
3 | increase(X) − counter X is increased by 1,
4 | max counter − all counters are set to the maximum value of any counter.
5 | A non-empty zero-indexed array A of M integers is given. This array represents consecutive operations:
6 | if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
7 | if A[K] = N + 1 then operation K is max counter.
8 | For example, given integer N = 5 and array A such that:
9 | A[0] = 3
10 | A[1] = 4
11 | A[2] = 4
12 | A[3] = 6
13 | A[4] = 1
14 | A[5] = 4
15 | A[6] = 4
16 | the values of the counters after each consecutive operation will be:
17 | (0, 0, 1, 0, 0)
18 | (0, 0, 1, 1, 0)
19 | (0, 0, 1, 2, 0)
20 | (2, 2, 2, 2, 2)
21 | (3, 2, 2, 2, 2)
22 | (3, 2, 2, 3, 2)
23 | (3, 2, 2, 4, 2)
24 | The goal is to calculate the value of every counter after all operations.
25 | Write a function:
26 | class Solution { public int[] solution(int N, int[] A); }
27 | that, given an integer N and a non-empty zero-indexed array A consisting of M integers, returns a sequence of integers representing the values of the counters.
28 | The sequence should be returned as:
29 | a structure Results (in C), or
30 | a vector of integers (in C++), or
31 | a record Results (in Pascal), or
32 | an array of integers (in any other programming language).
33 | For example, given:
34 | A[0] = 3
35 | A[1] = 4
36 | A[2] = 4
37 | A[3] = 6
38 | A[4] = 1
39 | A[5] = 4
40 | A[6] = 4
41 | the function should return [3, 2, 2, 4, 2], as explained above.
42 | Assume that:
43 | N and M are integers within the range [1..100,000];
44 | each element of array A is an integer within the range [1..N + 1].
45 | Complexity:
46 | expected worst-case time complexity is O(N+M);
47 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
48 | Elements of input arrays can be modified.
49 | */
50 |
51 | //SCORE: 100/100
52 | package countingelements;
53 |
54 | import java.util.Arrays;
55 |
56 | public class MaxCounter {
57 |
58 | public static void main(String[] args) {
59 | int[] A = new int[]{3,4,4,6,1,4,4};
60 | int N = 5;
61 | System.out.println(Arrays.toString(solution(N, A)));
62 | }
63 | public static int[] solution(int N, int[] A) {
64 | int[] counters = new int[N];
65 | int currMax = 0;
66 | int currMin = 0;
67 | for (int i = 0; i < A.length; i++) {
68 | if (A[i]<=N) {
69 | counters[A[i]-1] = Math.max(currMin, counters[A[i]-1]);
70 | counters[A[i]-1]++;
71 | currMax = Math.max(currMax, counters[A[i]-1]);
72 | }
73 | else if (A[i] == N+1) {
74 | currMin= currMax;
75 | }
76 | }
77 |
78 | for (int i = 0; i < counters.length; i++) {
79 | counters[i] = Math.max(counters[i], currMin);
80 | }
81 | return counters;
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/countingelements/MissingInteger.java:
--------------------------------------------------------------------------------
1 | /*
2 | Write a function:
3 | class Solution { public int solution(int[] A); }
4 | that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer that does not occur in A.
5 | For example, given:
6 | A[0] = 1
7 | A[1] = 3
8 | A[2] = 6
9 | A[3] = 4
10 | A[4] = 1
11 | A[5] = 2
12 | the function should return 5.
13 | Assume that:
14 | N is an integer within the range [1..100,000];
15 | each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
16 | Complexity:
17 | expected worst-case time complexity is O(N);
18 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
19 | Elements of input arrays can be modified.
20 | */
21 |
22 | //SCORE: 100/100
23 | package countingelements;
24 |
25 | import java.util.ArrayList;
26 | import java.util.stream.Collectors;
27 | import java.util.stream.IntStream;
28 |
29 |
30 | public class MissingInteger {
31 | public static void main(String[] args) {
32 | int[] A = new int[]{1,3,6,4,1,2};
33 | System.out.println(solution(A));
34 | }
35 |
36 | public static int solution(int[] A) {
37 | ArrayList numbers = IntStream.of(A).boxed().filter(x->x>0).sorted().distinct().collect(Collectors.toCollection(ArrayList::new));
38 | if (numbers.size() == 0)
39 | return 1;
40 | for (int i = 0; i < numbers.size(); i++) {
41 | if (numbers.get(i) != i+1)
42 | return i+1;
43 | }
44 | return numbers.size()+1;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/countingelements/PermCheck.java:
--------------------------------------------------------------------------------
1 | /*
2 | A non-empty zero-indexed array A consisting of N integers is given.
3 | A permutation is a sequence containing each element from 1 to N once, and only once.
4 | For example, array A such that:
5 | A[0] = 4
6 | A[1] = 1
7 | A[2] = 3
8 | A[3] = 2
9 | is a permutation, but array A such that:
10 | A[0] = 4
11 | A[1] = 1
12 | A[2] = 3
13 | is not a permutation, because value 2 is missing.
14 | The goal is to check whether array A is a permutation.
15 | Write a function:
16 | class Solution { public int solution(int[] A); }
17 | that, given a zero-indexed array A, returns 1 if array A is a permutation and 0 if it is not.
18 | For example, given array A such that:
19 | A[0] = 4
20 | A[1] = 1
21 | A[2] = 3
22 | A[3] = 2
23 | the function should return 1.
24 | Given array A such that:
25 | A[0] = 4
26 | A[1] = 1
27 | A[2] = 3
28 | the function should return 0.
29 | Assume that:
30 | N is an integer within the range [1..100,000];
31 | each element of array A is an integer within the range [1..1,000,000,000].
32 | Complexity:
33 | expected worst-case time complexity is O(N);
34 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
35 | Elements of input arrays can be modified.
36 | */
37 |
38 | //SCORE: 100/100
39 | package countingelements;
40 |
41 | import java.util.Arrays;
42 |
43 | public class PermCheck {
44 |
45 | public static void main(String[] args) {
46 | int[] A = new int[]{5,3,4,1,2,2,6};
47 | System.out.println(solution(A));
48 | }
49 | public static int solution(int[] A) {
50 | Arrays.sort(A);
51 | for (int i = 0; i < A.length; i++) {
52 | if (A[i] != i+1)
53 | return 0;
54 | }
55 | return 1;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/euclideanalgorithm/ChocoladeByNumbers.java:
--------------------------------------------------------------------------------
1 | /*
2 | Two positive integers N and M are given. Integer N represents the number of chocolates arranged in a circle, numbered from 0 to N − 1.
3 | You start to eat the chocolates. After eating a chocolate you leave only a wrapper.
4 | You begin with eating chocolate number 0. Then you omit the next M − 1 chocolates or wrappers on the circle, and eat the following one.
5 | More precisely, if you ate chocolate number X, then you will next eat the chocolate with number (X + M) modulo N (remainder of division).
6 | You stop eating when you encounter an empty wrapper.
7 | For example, given integers N = 10 and M = 4. You will eat the following chocolates: 0, 4, 8, 2, 6.
8 | The goal is to count the number of chocolates that you will eat, following the above rules.
9 | Write a function:
10 | class Solution { public int solution(int N, int M); }
11 | that, given two positive integers N and M, returns the number of chocolates that you will eat.
12 | For example, given integers N = 10 and M = 4. the function should return 5, as explained above.
13 | Assume that:
14 | N and M are integers within the range [1..1,000,000,000].
15 | Complexity:
16 | expected worst-case time complexity is O(log(N+M));
17 | expected worst-case space complexity is O(1).
18 | */
19 |
20 | //SCORE: 100/100
21 | package euclideanalgorithm;
22 |
23 | public class ChocoladeByNumbers {
24 |
25 | public static void main(String[] args) {
26 | int N =12;
27 | int M =3;
28 | int res=1;
29 | System.out.println(solution(N,M,res));
30 | }
31 |
32 | private static int solution(int N, int M, int res) {
33 | return N/greatestCommonDivisor(N,M,1);
34 | }
35 |
36 | private static int greatestCommonDivisor(int a, int b, int res) {
37 | if (a==b)
38 | return res*a;
39 | else if (a%2==0 && b%2==0)
40 | return greatestCommonDivisor (a/2, b/2, res*2);
41 | else if (a%2==0)
42 | return greatestCommonDivisor (a/2, b, res);
43 | else if (b%2==0)
44 | return greatestCommonDivisor (a, b/2, res);
45 | else if (a>b)
46 | return greatestCommonDivisor (a - b, b, res);
47 | else
48 | return greatestCommonDivisor (a, b - a, res);
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/euclideanalgorithm/CommonPrimeDivisors.java:
--------------------------------------------------------------------------------
1 | /*
2 | A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13.
3 | A prime D is called a prime divisor of a positive integer P if there exists a positive integer K such that D * K = P. For example, 2 and 5 are prime divisors of 20.
4 | You are given two positive integers N and M. The goal is to check whether the sets of prime divisors of integers N and M are exactly the same.
5 | For example, given:
6 | N = 15 and M = 75, the prime divisors are the same: {3, 5};
7 | N = 10 and M = 30, the prime divisors aren't the same: {2, 5} is not equal to {2, 3, 5};
8 | N = 9 and M = 5, the prime divisors aren't the same: {3} is not equal to {5}.
9 | Write a function:
10 | class Solution { public int solution(int[] A, int[] B); }
11 | that, given two non-empty zero-indexed arrays A and B of Z integers, returns the number of positions K for which the prime divisors of A[K] and B[K] are exactly the same.
12 | For example, given:
13 | A[0] = 15 B[0] = 75
14 | A[1] = 10 B[1] = 30
15 | A[2] = 3 B[2] = 5
16 | the function should return 1, because only one pair (15, 75) has the same set of prime divisors.
17 | Assume that:
18 | Z is an integer within the range [1..6,000];
19 | each element of arrays A, B is an integer within the range [1..2147483647].
20 | Complexity:
21 | expected worst-case time complexity is O(Z*log(max(A)+max(B))2);
22 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
23 | Elements of input arrays can be modified.
24 | */
25 |
26 | //SCORE: 100/100
27 | package euclideanalgorithm;
28 |
29 | public class CommonPrimeDivisors {
30 |
31 | public static void main(String[] args) {
32 | int[] A = new int[]{15,10,3};
33 | int[] B = new int[]{75,30,5};
34 | System.out.println(solution(A,B));
35 |
36 | }
37 |
38 | private static int solution(int[] A, int[] B) {
39 | int res=0;
40 | for (int i = 0; i < A.length; i++) {
41 | int x=A[i];
42 | int y=B[i];
43 | int gcd = gcd(x, y, 1);
44 | int gcdTmp=0;
45 | while(x!=1) {
46 | gcdTmp = gcd(x, gcd, 1);
47 | if(gcdTmp==1)
48 | break;
49 | x /= gcdTmp;
50 | }
51 | if (x!=1)
52 | continue;
53 |
54 | while(y!=1) {
55 | gcdTmp = gcd(y,gcd,1);
56 | if (gcdTmp==1)
57 | break;
58 | y /= gcdTmp;
59 | }
60 | if (y!=1)
61 | continue;
62 | res++;
63 | }
64 | return res;
65 | }
66 |
67 | private static int gcd(int a, int b, int res) {
68 | if (a==b)
69 | return res*a;
70 | else if (a%2==0 && b%2==0)
71 | return gcd (a/2, b/2, res*2);
72 | else if (a%2==0)
73 | return gcd (a/2, b, res);
74 | else if (b%2==0)
75 | return gcd (a, b/2, res);
76 | else if (a>b)
77 | return gcd (a - b, b, res);
78 | else
79 | return gcd (a, b - a, res);
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/fibonaccinumbers/FibFrog.java:
--------------------------------------------------------------------------------
1 | /*
2 | The Fibonacci sequence is defined using the following recursive formula:
3 | F(0) = 0
4 | F(1) = 1
5 | F(M) = F(M - 1) + F(M - 2) if M >= 2
6 | A small frog wants to get to the other side of a river. The frog is initially located at one bank of the river (position −1) and wants to get to the other bank (position N). The frog can jump over any distance F(K), where F(K) is the K-th Fibonacci number. Luckily, there are many leaves on the river, and the frog can jump between the leaves, but only in the direction of the bank at position N.
7 | The leaves on the river are represented in a zero-indexed array A consisting of N integers. Consecutive elements of array A represent consecutive positions from 0 to N − 1 on the river. Array A contains only 0s and/or 1s:
8 | 0 represents a position without a leaf;
9 | 1 represents a position containing a leaf.
10 | The goal is to count the minimum number of jumps in which the frog can get to the other side of the river (from position −1 to position N). The frog can jump between positions −1 and N (the banks of the river) and every position containing a leaf.
11 | For example, consider array A such that:
12 | A[0] = 0
13 | A[1] = 0
14 | A[2] = 0
15 | A[3] = 1
16 | A[4] = 1
17 | A[5] = 0
18 | A[6] = 1
19 | A[7] = 0
20 | A[8] = 0
21 | A[9] = 0
22 | A[10] = 0
23 | The frog can make three jumps of length F(5) = 5, F(3) = 2 and F(5) = 5.
24 | Write a function:
25 | class Solution { public int solution(int[] A); }
26 | that, given a zero-indexed array A consisting of N integers, returns the minimum number of jumps by which the frog can get to the other side of the river. If the frog cannot reach the other side of the river, the function should return −1.
27 | For example, given:
28 | A[0] = 0
29 | A[1] = 0
30 | A[2] = 0
31 | A[3] = 1
32 | A[4] = 1
33 | A[5] = 0
34 | A[6] = 1
35 | A[7] = 0
36 | A[8] = 0
37 | A[9] = 0
38 | A[10] = 0
39 | the function should return 3, as explained above.
40 | Assume that:
41 | N is an integer within the range [0..100,000];
42 | each element of array A is an integer that can have one of the following values: 0, 1.
43 | Complexity:
44 | expected worst-case time complexity is O(N*log(N));
45 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
46 | Elements of input arrays can be modified.
47 | */
48 |
49 | //SCORE: 100/100
50 | package fibonaccinumbers;
51 |
52 | import java.util.ArrayList;
53 | import java.util.List;
54 | import java.util.Stack;
55 |
56 | public class FibFrog {
57 | int number = 0;
58 | public static void main(String[] args) {
59 | int[] A = new int[]{0,0,0,1,1,0,1,0,0,0,0};
60 | System.out.println(solution(A));
61 | }
62 |
63 | public static int solution(int[] A) {
64 | List fibs = getFibonaciUpTo(A.length+1);
65 | boolean[] visited = new boolean[A.length];
66 | Stack stack= new Stack();
67 | stack.push(new Jump(-1,0));
68 | while(!stack.isEmpty()) {
69 | Jump currJump = stack.firstElement();
70 | stack.remove(0);
71 | int i = 0;
72 | while(currJump.pos + fibs.get(i)<= A.length) {
73 | if (currJump.pos + fibs.get(i) == A.length)
74 | return currJump.jumps + 1;
75 | if(A[fibs.get(i)+currJump.pos] == 1 && !visited[currJump.pos + fibs.get(i)]) {
76 | stack.push(new Jump(fibs.get(i)+currJump.pos, currJump.jumps+1));
77 | visited[fibs.get(i)+currJump.pos] = true;
78 | }
79 | i++;
80 | }
81 | }
82 | return -1;
83 | }
84 |
85 | public static List getFibonaciUpTo(int n) {
86 | List fibs = new ArrayList();
87 | fibs.add(0);
88 | fibs.add(1);
89 | int i =2;
90 | while(fibs.get(fibs.size()-1) <= n){
91 | fibs.add(fibs.get(i-1)+fibs.get(i-2));
92 | i++;
93 | }
94 | fibs.remove(0);
95 | fibs.remove(1);
96 | return fibs;
97 | }
98 |
99 | public static class Jump {
100 | int pos;
101 | int jumps;
102 | Jump(int p, int j) {
103 | pos = p;
104 | jumps = j;
105 | }
106 | }
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/src/fibonaccinumbers/Ladder.java:
--------------------------------------------------------------------------------
1 | /*
2 | You have to climb up a ladder. The ladder has exactly N rungs, numbered from 1 to N. With each step, you can ascend by one or two rungs. More precisely:
3 | with your first step you can stand on rung 1 or 2,
4 | if you are on rung K, you can move to rungs K + 1 or K + 2,
5 | finally you have to stand on rung N.
6 | Your task is to count the number of different ways of climbing to the top of the ladder.
7 | For example, given N = 4, you have five different ways of climbing, ascending by:
8 | 1, 1, 1 and 1 rung,
9 | 1, 1 and 2 rungs,
10 | 1, 2 and 1 rung,
11 | 2, 1 and 1 rungs, and
12 | 2 and 2 rungs.
13 | Given N = 5, you have eight different ways of climbing, ascending by:
14 | 1, 1, 1, 1 and 1 rung,
15 | 1, 1, 1 and 2 rungs,
16 | 1, 1, 2 and 1 rung,
17 | 1, 2, 1 and 1 rung,
18 | 1, 2 and 2 rungs,
19 | 2, 1, 1 and 1 rungs,
20 | 2, 1 and 2 rungs, and
21 | 2, 2 and 1 rung.
22 | The number of different ways can be very large, so it is sufficient to return the result modulo 2P, for a given integer P.
23 | Write a function:
24 | class Solution { public int[] solution(int[] A, int[] B); }
25 | that, given two non-empty zero-indexed arrays A and B of L integers, returns an array consisting of L integers specifying the consecutive answers; position I should contain the number of different ways of climbing the ladder with A[I] rungs modulo 2B[I].
26 | For example, given L = 5 and:
27 | A[0] = 4 B[0] = 3
28 | A[1] = 4 B[1] = 2
29 | A[2] = 5 B[2] = 4
30 | A[3] = 5 B[3] = 3
31 | A[4] = 1 B[4] = 1
32 | the function should return the sequence [5, 1, 8, 0, 1], as explained above.
33 | Assume that:
34 | L is an integer within the range [1..30,000];
35 | each element of array A is an integer within the range [1..L];
36 | each element of array B is an integer within the range [1..30].
37 | Complexity:
38 | expected worst-case time complexity is O(L);
39 | expected worst-case space complexity is O(L), beyond input storage (not counting the storage required for input arguments).
40 | Elements of input arrays can be modified.
41 | */
42 |
43 | //SCORE: 100/75
44 | package fibonaccinumbers;
45 |
46 | import java.math.BigInteger;
47 | import java.util.Arrays;
48 |
49 | public class Ladder {
50 | int number = 0;
51 | public static void main(String[] args) {
52 | int[] A = new int[]{4,4,5,5,1};
53 | int[] B = new int[]{3,2,4,3,1};
54 | System.out.println(Arrays.toString(solution(A,B)));
55 | }
56 |
57 | public static int[] solution(int[] A, int[] B) {
58 | BigInteger[] fibs = new BigInteger[A.length+2];
59 | fibs[0] = new BigInteger("0");
60 | fibs[1] = new BigInteger("1");
61 | for (int i = 2; i < A.length+2; i++) {
62 | fibs[i] = fibs[i-1].add(fibs[i-2]);
63 | }
64 | int[] res = new int[A.length];
65 | for (int i = 0; i < B.length; i++) {
66 | BigInteger currPow = new BigInteger(String.valueOf((long)Math.pow(2, B[i])));
67 | res[i] = fibs[A[i]+1].mod(currPow).intValue();
68 | }
69 | return res;
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/greedyalgorithms/TieRope.java:
--------------------------------------------------------------------------------
1 | /*
2 | There are N ropes numbered from 0 to N − 1, whose lengths are given in a zero-indexed array A, lying on the floor in a line. For each I (0 ≤ I < N), the length of rope I on the line is A[I].
3 | We say that two ropes I and I + 1 are adjacent. Two adjacent ropes can be tied together with a knot, and the length of the tied rope is the sum of lengths of both ropes. The resulting new rope can then be tied again.
4 | For a given integer K, the goal is to tie the ropes in such a way that the number of ropes whose length is greater than or equal to K is maximal.
5 | For example, consider K = 4 and array A such that:
6 | A[0] = 1
7 | A[1] = 2
8 | A[2] = 3
9 | A[3] = 4
10 | A[4] = 1
11 | A[5] = 1
12 | A[6] = 3
13 | The ropes are shown in the figure below.
14 |
15 | We can tie:
16 | rope 1 with rope 2 to produce a rope of length A[1] + A[2] = 5;
17 | rope 4 with rope 5 with rope 6 to produce a rope of length A[4] + A[5] + A[6] = 5.
18 | After that, there will be three ropes whose lengths are greater than or equal to K = 4. It is not possible to produce four such ropes.
19 | Write a function:
20 | int solution(int K, int A[], int N);
21 | that, given an integer K and a non-empty zero-indexed array A of N integers, returns the maximum number of ropes of length greater than or equal to K that can be created.
22 | For example, given K = 4 and array A such that:
23 | A[0] = 1
24 | A[1] = 2
25 | A[2] = 3
26 | A[3] = 4
27 | A[4] = 1
28 | A[5] = 1
29 | A[6] = 3
30 | the function should return 3, as explained above.
31 | Assume that:
32 | N is an integer within the range [1..100,000];
33 | K is an integer within the range [1..1,000,000,000];
34 | each element of array A is an integer within the range [1..1,000,000,000].
35 | Complexity:
36 | expected worst-case time complexity is O(N);
37 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
38 | Elements of input arrays can be modified.
39 | */
40 |
41 | //SCORE: 100/100
42 | package greedyalgorithms;
43 |
44 | public class TieRope {
45 | public static void main (String[] args) {
46 | int[] A = new int[]{1,2,3,4,1,1,3};
47 | int K = 4;
48 | System.out.println(solution(A, K));
49 | }
50 |
51 | public static int solution(int[] A, int K) {
52 | int res=0;
53 | int tmp=0;
54 | for (int i = 0; i < A.length; i++) {
55 | tmp+=A[i];
56 | if (tmp>=K) {
57 | res++;
58 | tmp=0;
59 | }
60 | }
61 | return res;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/leader/Dominator.java:
--------------------------------------------------------------------------------
1 | /*
2 | A zero-indexed array A consisting of N integers is given. The dominator of array A is the value that occurs in more than half of the elements of A.
3 | For example, consider array A such that
4 | A[0] = 3 A[1] = 4 A[2] = 3
5 | A[3] = 2 A[4] = 3 A[5] = -1
6 | A[6] = 3 A[7] = 3
7 | The dominator of A is 3 because it occurs in 5 out of 8 elements of A (namely in those with indices 0, 2, 4, 6 and 7) and 5 is more than a half of 8.
8 | Write a function
9 | class Solution { public int solution(int[] A); }
10 | that, given a zero-indexed array A consisting of N integers, returns index of any element of array A in which the dominator of A occurs. The function should return −1 if array A does not have a dominator.
11 | Assume that:
12 | N is an integer within the range [0..100,000];
13 | each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
14 | For example, given array A such that
15 | A[0] = 3 A[1] = 4 A[2] = 3
16 | A[3] = 2 A[4] = 3 A[5] = -1
17 | A[6] = 3 A[7] = 3
18 | the function may return 0, 2, 4, 6 or 7, as explained above.
19 | Complexity:
20 | expected worst-case time complexity is O(N);
21 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
22 | Elements of input arrays can be modified.
23 | */
24 |
25 | //SCORE: 100/100
26 | package leader;
27 |
28 | import java.util.Stack;
29 |
30 | public class Dominator {
31 | public static void main (String[] args) {
32 | int[] A = new int[]{3, 4, 3, 2, 3, -1, 3, 3};
33 | System.out.println(solution(A));
34 |
35 | }
36 |
37 | public static int solution(int[] A) {
38 | Stack stack = new Stack();
39 | for (int i = 0; i < A.length; i++) {
40 | if (stack.isEmpty()) {
41 | stack.push(A[i]);
42 | continue;
43 | }
44 | if (stack.peek() == A[i])
45 | stack.push(A[i]);
46 | else
47 | stack.pop();
48 | }
49 | if (stack.isEmpty())
50 | return -1;
51 | int domCandidate = stack.peek();
52 | int occurances = 0;
53 | int randomIndex=-1;
54 | for (int i = 0; i < A.length; i++) {
55 | if(A[i] == domCandidate) {
56 | occurances++;
57 | randomIndex = i;
58 | }
59 | }
60 |
61 | return occurances>A.length/2?randomIndex:-1;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/leader/EquiLeader.java:
--------------------------------------------------------------------------------
1 | /*
2 | A non-empty zero-indexed array A consisting of N integers is given.
3 | The leader of this array is the value that occurs in more than half of the elements of A.
4 | An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have leaders of the same value.
5 | For example, given array A such that:
6 | A[0] = 4
7 | A[1] = 3
8 | A[2] = 4
9 | A[3] = 4
10 | A[4] = 4
11 | A[5] = 2
12 | we can find two equi leaders:
13 | 0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4.
14 | 2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4.
15 | The goal is to count the number of equi leaders. Write a function:
16 | class Solution { public int solution(int[] A); }
17 | that, given a non-empty zero-indexed array A consisting of N integers, returns the number of equi leaders.
18 | For example, given:
19 | A[0] = 4
20 | A[1] = 3
21 | A[2] = 4
22 | A[3] = 4
23 | A[4] = 4
24 | A[5] = 2
25 | the function should return 2, as explained above.
26 | Assume that:
27 | N is an integer within the range [1..100,000];
28 | each element of array A is an integer within the range [−1,000,000,000..1,000,000,000].
29 | Complexity:
30 | expected worst-case time complexity is O(N);
31 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
32 | Elements of input arrays can be modified.
33 | */
34 |
35 | //SCORE: 100/100
36 | package leader;
37 |
38 | import java.util.Stack;
39 |
40 | public class EquiLeader {
41 | public static void main (String[] args) {
42 | int[] A = new int[]{4,3,4,4,4,2};
43 | System.out.println(solution(A));
44 |
45 | }
46 | public static int solution(int[] A) {
47 |
48 | //check if it is dominator at all
49 | Stack stack = new Stack();
50 | for (int i = 0; i < A.length; i++) {
51 | if (stack.isEmpty()) {
52 | stack.push(A[i]);
53 | continue;
54 | }
55 | if (stack.peek() == A[i])
56 | stack.push(A[i]);
57 | else
58 | stack.pop();
59 | }
60 | if (stack.isEmpty())
61 | return 0; //there's no dominator
62 | int dominator = stack.peek();
63 | int domOccurances = 0;
64 | for (int i = 0; i < A.length; i++) {
65 | if(A[i] == dominator)
66 | domOccurances++;
67 | }
68 | if (domOccurances <= A.length/2)
69 | return 0;//not dominator
70 | int nonDomOccurances = A.length - domOccurances;
71 | stack.clear();
72 | int dom=0;
73 | int nonDom=0;
74 | int equiLeaders=0;
75 | for (int i = 0; i < A.length; i++) {
76 | if (A[i] == dominator)
77 | dom++;
78 | else
79 | nonDom++;
80 | if (dom>nonDom && (domOccurances - dom) > (nonDomOccurances-nonDom))
81 | equiLeaders++;
82 | }
83 | return equiLeaders;
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/src/maximumslice/MaxDoubleSliceSum.java:
--------------------------------------------------------------------------------
1 | /*
2 | A non-empty zero-indexed array A consisting of N integers is given.
3 | A triplet (X, Y, Z), such that 0 ≤ X < Y < Z < N, is called a double slice.
4 | The sum of double slice (X, Y, Z) is the total of A[X + 1] + A[X + 2] + ... + A[Y − 1] + A[Y + 1] + A[Y + 2] + ... + A[Z − 1].
5 | For example, array A such that:
6 | A[0] = 3
7 | A[1] = 2
8 | A[2] = 6
9 | A[3] = -1
10 | A[4] = 4
11 | A[5] = 5
12 | A[6] = -1
13 | A[7] = 2
14 | contains the following example double slices:
15 | double slice (0, 3, 6), sum is 2 + 6 + 4 + 5 = 17,
16 | double slice (0, 3, 7), sum is 2 + 6 + 4 + 5 − 1 = 16,
17 | double slice (3, 4, 5), sum is 0.
18 | The goal is to find the maximal sum of any double slice.
19 | Write a function:
20 | class Solution { public int solution(int[] A); }
21 | that, given a non-empty zero-indexed array A consisting of N integers, returns the maximal sum of any double slice.
22 | For example, given:
23 | A[0] = 3
24 | A[1] = 2
25 | A[2] = 6
26 | A[3] = -1
27 | A[4] = 4
28 | A[5] = 5
29 | A[6] = -1
30 | A[7] = 2
31 | the function should return 17, because no double slice of array A has a sum of greater than 17.
32 | Assume that:
33 | N is an integer within the range [3..100,000];
34 | each element of array A is an integer within the range [−10,000..10,000].
35 | Complexity:
36 | expected worst-case time complexity is O(N);
37 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
38 | Elements of input arrays can be modified.
39 | */
40 |
41 | //SCORE: 100/100
42 | package maximumslice;
43 |
44 | public class MaxDoubleSliceSum {
45 | public static void main(String[] args) {
46 | int[] A = new int[]{3,2,6,-1,4,5,-1,2};
47 | System.out.println(solution(A));
48 |
49 | }
50 |
51 | public static int solution(int[] A) {
52 | int max = 0;
53 | int[] A1 = new int[A.length];
54 | int[] A2 = new int[A.length];
55 | for (int i = 1; i < A.length-1; i++) {
56 | A1[i] = Math.max(A1[i-1] + A[i], 0);
57 | }
58 | for (int i = A.length -2; i >=1; i--) {
59 | A2[i] = Math.max(A2[i+1] + A[i], 0);
60 | }
61 |
62 | for (int i = 1; i < A.length-1; i++) {
63 | max = Math.max(max, A1[i-1] + A2[i+1]);
64 | }
65 | return max;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/maximumslice/MaxProfit.java:
--------------------------------------------------------------------------------
1 | /*
2 | A zero-indexed array A consisting of N integers is given. It contains daily prices of a stock share for a period of N consecutive days. If a single share was bought on day P and sold on day Q, where 0 ≤ P ≤ Q < N, then the profit of such transaction is equal to A[Q] − A[P], provided that A[Q] ≥ A[P]. Otherwise, the transaction brings loss of A[P] − A[Q].
3 | For example, consider the following array A consisting of six elements such that:
4 | A[0] = 23171
5 | A[1] = 21011
6 | A[2] = 21123
7 | A[3] = 21366
8 | A[4] = 21013
9 | A[5] = 21367
10 | If a share was bought on day 0 and sold on day 2, a loss of 2048 would occur because A[2] − A[0] = 21123 − 23171 = −2048. If a share was bought on day 4 and sold on day 5, a profit of 354 would occur because A[5] − A[4] = 21367 − 21013 = 354. Maximum possible profit was 356. It would occur if a share was bought on day 1 and sold on day 5.
11 | Write a function,
12 | class Solution { public int solution(int[] A); }
13 | that, given a zero-indexed array A consisting of N integers containing daily prices of a stock share for a period of N consecutive days, returns the maximum possible profit from one transaction during this period. The function should return 0 if it was impossible to gain any profit.
14 | For example, given array A consisting of six elements such that:
15 | A[0] = 23171
16 | A[1] = 21011
17 | A[2] = 21123
18 | A[3] = 21366
19 | A[4] = 21013
20 | A[5] = 21367
21 | the function should return 356, as explained above.
22 | Assume that:
23 | N is an integer within the range [0..400,000];
24 | each element of array A is an integer within the range [0..200,000].
25 | Complexity:
26 | expected worst-case time complexity is O(N);
27 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
28 | Elements of input arrays can be modified.
29 | */
30 |
31 | //SCORE: 100/100
32 | package maximumslice;
33 |
34 | import java.util.Arrays;
35 |
36 | public class MaxProfit {
37 | public static void main(String[] args) {
38 | int[] A = new int[]{23171, 21011,21123, 21366, 21013, 21367};
39 | System.out.println(solution(A));
40 | }
41 |
42 | public static int solution(int[] A) {
43 | if (A.length == 0)
44 | return 0;
45 | int[] array = new int[A.length];
46 | array[0] = 0;
47 | for (int i = 1; i < A.length; i++) {
48 | array[i] = A[i] - A[i-1];
49 | }
50 | return goldenMaxSlice(array);
51 | }
52 |
53 | public static int goldenMaxSlice(int[] A) {
54 | int arrMax = Arrays.stream(A).max().getAsInt();
55 | if (arrMax < 0)
56 | return arrMax;
57 | int maxEnding = 0;
58 | int maxSlice = 0;
59 | for (int i = 0; i < A.length; i++) {
60 | maxEnding = (maxEnding + A[i])>0? (maxEnding + A[i]): 0;
61 | maxSlice = maxSlice>maxEnding? maxSlice:maxEnding;
62 | }
63 | return maxSlice;
64 | }
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/src/maximumslice/MaxSliceSum.java:
--------------------------------------------------------------------------------
1 | /*
2 | A non-empty zero-indexed array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P ≤ Q < N, is called a slice of array A. The sum of a slice (P, Q) is the total of A[P] + A[P+1] + ... + A[Q].
3 | Write a function:
4 | int solution(int A[], int N);
5 | that, given an array A consisting of N integers, returns the maximum sum of any slice of A.
6 | For example, given array A such that:
7 | A[0] = 3 A[1] = 2 A[2] = -6
8 | A[3] = 4 A[4] = 0
9 | the function should return 5 because:
10 | (3, 4) is a slice of A that has sum 4,
11 | (2, 2) is a slice of A that has sum −6,
12 | (0, 1) is a slice of A that has sum 5,
13 | no other slice of A has sum greater than (0, 1).
14 | Assume that:
15 | N is an integer within the range [1..1,000,000];
16 | each element of array A is an integer within the range [−1,000,000..1,000,000];
17 | the result will be an integer within the range [−2,147,483,648..2,147,483,647].
18 | Complexity:
19 | expected worst-case time complexity is O(N);
20 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
21 | Elements of input arrays can be modified.
22 | */
23 |
24 | //SCORE: 100/100
25 | package maximumslice;
26 |
27 | public class MaxSliceSum {
28 | public static void main(String[] args) {
29 | // TODO Auto-generated method stub
30 | int[] A = new int[]{3,2,-6,4,0};
31 | System.out.println(solution(A));
32 | }
33 |
34 | public static int solution(int[] A) {
35 | int max=Integer.MIN_VALUE;
36 | for (int i = 0; i < A.length; i++) {
37 | max = A[i]>max?A[i]:max;
38 | }
39 | if(max<=0)
40 | return max;
41 |
42 | int maxSliceSum = 0;
43 | int currentSum = 0;
44 | for (int i = 0; i < A.length; i++) {
45 | currentSum = (currentSum+A[i])>0?(currentSum+A[i]):0;
46 | maxSliceSum=currentSum>maxSliceSum?currentSum:maxSliceSum;
47 | }
48 | return maxSliceSum;
49 | }
50 |
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/src/prefixsums/CountDiv.java:
--------------------------------------------------------------------------------
1 | /*
2 | Write a function:
3 | class Solution { public int solution(int A, int B, int K); }
4 | that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:
5 | { i : A ≤ i ≤ B, i mod K = 0 }
6 | For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10.
7 | Assume that:
8 | A and B are integers within the range [0..2,000,000,000];
9 | K is an integer within the range [1..2,000,000,000];
10 | A ≤ B.
11 | Complexity:
12 | expected worst-case time complexity is O(1);
13 | expected worst-case space complexity is O(1).
14 | */
15 |
16 | //SCORE: 100/100
17 | package prefixsums;
18 |
19 | public class CountDiv {
20 | public static void main(String[] args) {
21 | int A = 6;
22 | int B = 11;
23 | int K = 2;
24 | System.out.println(solution(A,B,K));
25 | }
26 | public static int solution(int A, int B, int K) {
27 | if (A%K==0)
28 | return B/K - A/K + 1;
29 | return B/K - A/K;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/prefixsums/GenomicRangeQuery.java:
--------------------------------------------------------------------------------
1 | /*
2 | A DNA sequence can be represented as a string consisting of the letters A, C, G and T, which correspond to the types of successive nucleotides in the sequence. Each nucleotide has an impact factor, which is an integer. Nucleotides of types A, C, G and T have impact factors of 1, 2, 3 and 4, respectively. You are going to answer several queries of the form: What is the minimal impact factor of nucleotides contained in a particular part of the given DNA sequence?
3 | The DNA sequence is given as a non-empty string S = S[0]S[1]...S[N-1] consisting of N characters. There are M queries, which are given in non-empty arrays P and Q, each consisting of M integers. The K-th query (0 ≤ K < M) requires you to find the minimal impact factor of nucleotides contained in the DNA sequence between positions P[K] and Q[K] (inclusive).
4 | For example, consider string S = CAGCCTA and arrays P, Q such that:
5 | P[0] = 2 Q[0] = 4
6 | P[1] = 5 Q[1] = 5
7 | P[2] = 0 Q[2] = 6
8 | The answers to these M = 3 queries are as follows:
9 | The part of the DNA between positions 2 and 4 contains nucleotides G and C (twice), whose impact factors are 3 and 2 respectively, so the answer is 2.
10 | The part between positions 5 and 5 contains a single nucleotide T, whose impact factor is 4, so the answer is 4.
11 | The part between positions 0 and 6 (the whole string) contains all nucleotides, in particular nucleotide A whose impact factor is 1, so the answer is 1.
12 | Write a function:
13 | class Solution { public int[] solution(String S, int[] P, int[] Q); }
14 | that, given a non-empty zero-indexed string S consisting of N characters and two non-empty zero-indexed arrays P and Q consisting of M integers, returns an array consisting of M integers specifying the consecutive answers to all queries.
15 | The sequence should be returned as:
16 | a Results structure (in C), or
17 | a vector of integers (in C++), or
18 | a Results record (in Pascal), or
19 | an array of integers (in any other programming language).
20 | For example, given the string S = CAGCCTA and arrays P, Q such that:
21 | P[0] = 2 Q[0] = 4
22 | P[1] = 5 Q[1] = 5
23 | P[2] = 0 Q[2] = 6
24 | the function should return the values [2, 4, 1], as explained above.
25 | Assume that:
26 | N is an integer within the range [1..100,000];
27 | M is an integer within the range [1..50,000];
28 | each element of arrays P, Q is an integer within the range [0..N − 1];
29 | P[K] ≤ Q[K], where 0 ≤ K < M;
30 | string S consists only of upper-case English letters A, C, G, T.
31 | Complexity:
32 | expected worst-case time complexity is O(N+M);
33 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
34 | Elements of input arrays can be modified.
35 | */
36 |
37 | //SCORE:100/100
38 | package prefixsums;
39 |
40 | import java.util.ArrayList;
41 | import java.util.Arrays;
42 | import java.util.HashMap;
43 | import java.util.Map;
44 |
45 | public class GenomicRangeQuery {
46 | public static void main(String[] args) {
47 | int[] P = new int[]{2,5,0};
48 | int[] Q = new int[]{4,5,6};
49 | String S = "CAGCCTA";
50 | System.out.println(Arrays.toString(solution(S,P,Q)));
51 | }
52 | public static int[] solution(String S, int[] P, int[] Q) {
53 | Map> prefSums = getPrefSum(S);
54 | int[] res = new int[P.length];
55 | for (int i = 0; i < Q.length; i++) {
56 | for (int j = 1; j < 5; j++) {
57 | int high = prefSums.get(j).get(Q[i]);
58 | int low = P[i]==0? 0 :prefSums.get(j).get(P[i] -1);
59 | if (high - low > 0) {
60 | res[i]=j;
61 | break;
62 | }
63 | }
64 | }
65 | return res;
66 | }
67 |
68 | public static Map> getPrefSum(String s) {
69 | Map> prefSums = new HashMap>();
70 | for (int j = 0; j < 4; j++) {
71 | prefSums.put(j+1, new ArrayList());
72 | }
73 | int[] counters = new int[4];
74 | for (int i = 0; i < s.length(); i++) {
75 | switch(s.charAt(i)) {
76 | case 'A': counters[0]++;break;
77 |
78 | case 'C':counters[1]++;break;
79 |
80 | case 'G':counters[2]++;break;
81 |
82 | case 'T': counters[3]++;break;
83 |
84 | default: break;
85 | }
86 | for (int j = 0; j < 4; j++) {
87 | prefSums.get(j+1).add(counters[j]);
88 | }
89 | }
90 | return prefSums;
91 | }
92 |
93 | }
94 |
--------------------------------------------------------------------------------
/src/prefixsums/MinAvgTwoSlice.java:
--------------------------------------------------------------------------------
1 | /*
2 | A non-empty zero-indexed array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P < Q < N, is called a slice of array A (notice that the slice contains at least two elements). The average of a slice (P, Q) is the sum of A[P] + A[P + 1] + ... + A[Q] divided by the length of the slice. To be precise, the average equals (A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1).
3 | For example, array A such that:
4 | A[0] = 4
5 | A[1] = 2
6 | A[2] = 2
7 | A[3] = 5
8 | A[4] = 1
9 | A[5] = 5
10 | A[6] = 8
11 | contains the following example slices:
12 | slice (1, 2), whose average is (2 + 2) / 2 = 2;
13 | slice (3, 4), whose average is (5 + 1) / 2 = 3;
14 | slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5.
15 | The goal is to find the starting position of a slice whose average is minimal.
16 | Write a function:
17 | class Solution { public int solution(int[] A); }
18 | that, given a non-empty zero-indexed array A consisting of N integers, returns the starting position of the slice with the minimal average. If there is more than one slice with a minimal average, you should return the smallest starting position of such a slice.
19 | For example, given array A such that:
20 | A[0] = 4
21 | A[1] = 2
22 | A[2] = 2
23 | A[3] = 5
24 | A[4] = 1
25 | A[5] = 5
26 | A[6] = 8
27 | the function should return 1, as explained above.
28 | Assume that:
29 | N is an integer within the range [2..100,000];
30 | each element of array A is an integer within the range [−10,000..10,000].
31 | Complexity:
32 | expected worst-case time complexity is O(N);
33 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
34 | Elements of input arrays can be modified.
35 | */
36 |
37 | //SCORE: 100/100 (both solutions)
38 | package prefixsums;
39 |
40 |
41 | public class MinAvgTwoSlice {
42 | public static void main(String[] args) {
43 | int[] A = new int[]{4,2,2,5,1,5,8};
44 | System.out.println(solution1(A));
45 | }
46 |
47 | //using caterpillar method (min value will be inside 2 or 3 element slices)
48 | public static int solution(int[] A) {
49 | int front=1;
50 | int back= 0;
51 | int res = 0;
52 | int curr = A[0]+A[1];
53 | double min = (double)curr/2;
54 | double tmpMin = min;
55 |
56 | while (true) {
57 | if (front - back == 1) {
58 | front++;
59 | if (front == A.length)
60 | return res;
61 | curr += A[front];
62 | }
63 | else {
64 | curr -= A[back];
65 | back++;
66 | }
67 |
68 | tmpMin=(double)curr/(front-back+1);
69 | if (tmpMin < min) {
70 | res = back;
71 | min = tmpMin;
72 | }
73 | }
74 | }
75 |
76 | public static int solution1(int[] A) {
77 | int res = 0;
78 | double min = (double)(A[0]+A[1])/2;
79 |
80 | for (int j = 0; j < A.length-2; j++) {
81 | if ((double)(A[j] + A[j+1]) / 2 < min){
82 | min = (double)(A[j] + A[j+1]) / 2;
83 | res=j;
84 | }
85 | if ((double)(A[j] + A[j+1] + A[j+2]) / 3 < min){
86 | min = (double)(A[j] + A[j+1] + A[j+2]) / 3;
87 | res=j;
88 | }
89 | }
90 |
91 | if ((double)(A[A.length-1] + A[A.length-2])/2 < min)
92 | return A.length - 2;
93 | return res;
94 | }
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/src/prefixsums/PassingCars.java:
--------------------------------------------------------------------------------
1 | /*
2 | A non-empty zero-indexed array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road.
3 | Array A contains only 0s and/or 1s:
4 | 0 represents a car traveling east,
5 | 1 represents a car traveling west.
6 | The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west.
7 | For example, consider array A such that:
8 | A[0] = 0
9 | A[1] = 1
10 | A[2] = 0
11 | A[3] = 1
12 | A[4] = 1
13 | We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).
14 | Write a function:
15 | class Solution { public int solution(int[] A); }
16 | that, given a non-empty zero-indexed array A of N integers, returns the number of passing cars.
17 | The function should return −1 if the number of passing cars exceeds 1,000,000,000.
18 | For example, given:
19 | A[0] = 0
20 | A[1] = 1
21 | A[2] = 0
22 | A[3] = 1
23 | A[4] = 1
24 | the function should return 5, as explained above.
25 | Assume that:
26 | N is an integer within the range [1..100,000];
27 | each element of array A is an integer that can have one of the following values: 0, 1.
28 | Complexity:
29 | expected worst-case time complexity is O(N);
30 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
31 | Elements of input arrays can be modified.
32 | */
33 |
34 | //SCORE: 100/100
35 | package prefixsums;
36 |
37 | public class PassingCars {
38 | public static void main(String[] args) {
39 | int[] A = new int[]{0,1,0,1,1};
40 | System.out.println(solution(A));
41 | }
42 | public static int solution(int[] A) {
43 | int res = 0;
44 | int ones = 0;
45 | for (int i = A.length-1; i >= 0; i--) {
46 | if (A[i] == 1)
47 | ones++;
48 | else {
49 | res += ones;
50 | if (res > 1000000000)
51 | return -1;
52 | }
53 | }
54 | return res;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/primeandcompositenumbers/CountFactors.java:
--------------------------------------------------------------------------------
1 | /*
2 | A positive integer D is a factor of a positive integer N if there exists an integer M such that N = D * M.
3 | For example, 6 is a factor of 24, because M = 4 satisfies the above condition (24 = 6 * 4).
4 | Write a function:
5 | class Solution { public int solution(int N); }
6 | that, given a positive integer N, returns the number of its factors.
7 | For example, given N = 24, the function should return 8, because 24 has 8 factors, namely 1, 2, 3, 4, 6, 8, 12, 24. There are no other factors of 24.
8 | Assume that:
9 | N is an integer within the range [1..2,147,483,647].
10 | Complexity:
11 | expected worst-case time complexity is O(sqrt(N));
12 | expected worst-case space complexity is O(1).
13 | */
14 |
15 | //Score: 100/100
16 | package primeandcompositenumbers;
17 |
18 | public class CountFactors {
19 |
20 | public static void main(String[] args) {
21 | System.out.println(solution(24));
22 | }
23 |
24 | public static int solution(int N) {
25 | int res = 0;
26 | for (int i = 1; (long)i*i <=N ; i++) {
27 | if (i*i == N)
28 | return ++res;
29 | else if(N%i == 0)
30 | res+=2;
31 | }
32 | return res;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/primeandcompositenumbers/Flags.java:
--------------------------------------------------------------------------------
1 | /*
2 | A non-empty zero-indexed array A consisting of N integers is given. A peak is an array element which is larger than its neighbours. More precisely, it is an index P such that 0 < P < N − 1 and A[P − 1] < A[P] > A[P + 1].
3 | For example, the following array A:
4 | A[0] = 1
5 | A[1] = 5
6 | A[2] = 3
7 | A[3] = 4
8 | A[4] = 3
9 | A[5] = 4
10 | A[6] = 1
11 | A[7] = 2
12 | A[8] = 3
13 | A[9] = 4
14 | A[10] = 6
15 | A[11] = 2
16 | has exactly four peaks: elements 1, 3, 5 and 10.
17 | You are going on a trip to a range of mountains whose relative heights are represented by array A, as shown in a figure below. You have to choose how many flags you should take with you. The goal is to set the maximum number of flags on the peaks, according to certain rules.
18 |
19 | Flags can only be set on peaks. What's more, if you take K flags, then the distance between any two flags should be greater than or equal to K. The distance between indices P and Q is the absolute value |P − Q|.
20 | For example, given the mountain range represented by array A, above, with N = 12, if you take:
21 | two flags, you can set them on peaks 1 and 5;
22 | three flags, you can set them on peaks 1, 5 and 10;
23 | four flags, you can set only three flags, on peaks 1, 5 and 10.
24 | You can therefore set a maximum of three flags in this case.
25 | Write a function:
26 | class Solution { public int solution(int[] A); }
27 | that, given a non-empty zero-indexed array A of N integers, returns the maximum number of flags that can be set on the peaks of the array.
28 | For example, the following array A:
29 | A[0] = 1
30 | A[1] = 5
31 | A[2] = 3
32 | A[3] = 4
33 | A[4] = 3
34 | A[5] = 4
35 | A[6] = 1
36 | A[7] = 2
37 | A[8] = 3
38 | A[9] = 4
39 | A[10] = 6
40 | A[11] = 2
41 | the function should return 3, as explained above.
42 | Assume that:
43 | N is an integer within the range [1..200,000];
44 | each element of array A is an integer within the range [0..1,000,000,000].
45 | Complexity:
46 | expected worst-case time complexity is O(N);
47 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
48 | Elements of input arrays can be modified.
49 | */
50 |
51 | //Score: 100/14
52 | package primeandcompositenumbers;
53 |
54 | import java.util.ArrayList;
55 |
56 | public class Flags {
57 |
58 | public static void main(String[] args) {
59 | int[] N = new int[] {1,5,3,4,3,4,1,2,3,4,6,2};
60 | System.out.println(solution(N));
61 | }
62 |
63 | public static int solution(int[] A) {
64 | return flags(A);
65 | }
66 |
67 | public static int[] nextPeak(int[] A) {
68 | int N = A.length;
69 | ArrayList peaks = createPeaks(A);
70 | int[] next = new int[N];
71 | next[N-1] = -1;
72 | for (int i = N-2; i > -1; i--) {
73 | if(peaks.contains(i))
74 | next[i] = i;
75 | else
76 | next[i] = next[i+1];
77 | }
78 | return next;
79 | }
80 |
81 | public static ArrayList createPeaks(int[] A) {
82 | ArrayList peaks = new ArrayList();
83 | for (int i = 1; i < A.length-1; i++)
84 | if (A[i] > A[i-1] && A[i] > A[i+1])
85 | peaks.add(i);
86 | return peaks;
87 | }
88 |
89 | public static int flags(int[] A) {
90 | int N = A.length;
91 | int[] next = nextPeak(A);
92 | int i = 1;
93 | int result = 0;
94 | while ((i-1)*i <= N) {
95 | int pos = 0;
96 | int num = 0;
97 | while (pos < N && num < i) {
98 | pos = next[pos];
99 | if (pos == -1)
100 | break;
101 | num += 1;
102 | pos += i;
103 | }
104 | result = Math.max(result, num);
105 | i++;
106 | }
107 | return result;
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/src/primeandcompositenumbers/MinPerimeterRectangle.java:
--------------------------------------------------------------------------------
1 | /*
2 | An integer N is given, representing the area of some rectangle.
3 | The area of a rectangle whose sides are of length A and B is A * B, and the perimeter is 2 * (A + B).
4 | The goal is to find the minimal perimeter of any rectangle whose area equals N. The sides of this rectangle should be only integers.
5 | For example, given integer N = 30, rectangles of area 30 are:
6 | (1, 30), with a perimeter of 62,
7 | (2, 15), with a perimeter of 34,
8 | (3, 10), with a perimeter of 26,
9 | (5, 6), with a perimeter of 22.
10 | Write a function:
11 | class Solution { public int solution(int N); }
12 | that, given an integer N, returns the minimal perimeter of any rectangle whose area is exactly equal to N.
13 | For example, given an integer N = 30, the function should return 22, as explained above.
14 | Assume that:
15 | N is an integer within the range [1..1,000,000,000].
16 | Complexity:
17 | expected worst-case time complexity is O(sqrt(N));
18 | expected worst-case space complexity is O(1).
19 | */
20 |
21 | //Score: 100/100
22 | package primeandcompositenumbers;
23 |
24 | public class MinPerimeterRectangle {
25 |
26 | public static void main(String[] args) {
27 | System.out.println(solution(30));
28 | }
29 |
30 | public static int solution(int N) {
31 | int min = Integer.MAX_VALUE;
32 | for (int i = 1; i*i <= N; i++) {
33 | if (N % i == 0)
34 | min = 2*(i+N/i) A[P + 1].
4 | For example, the following array A:
5 | A[0] = 1
6 | A[1] = 2
7 | A[2] = 3
8 | A[3] = 4
9 | A[4] = 3
10 | A[5] = 4
11 | A[6] = 1
12 | A[7] = 2
13 | A[8] = 3
14 | A[9] = 4
15 | A[10] = 6
16 | A[11] = 2
17 | has exactly three peaks: 3, 5, 10.
18 | We want to divide this array into blocks containing the same number of elements. More precisely, we want to choose a number K that will yield the following blocks:
19 | A[0], A[1], ..., A[K − 1],
20 | A[K], A[K + 1], ..., A[2K − 1],
21 | ...
22 | A[N − K], A[N − K + 1], ..., A[N − 1].
23 | What's more, every block should contain at least one peak. Notice that extreme elements of the blocks (for example A[K − 1] or A[K]) can also be peaks, but only if they have both neighbors (including one in an adjacent blocks).
24 | The goal is to find the maximum number of blocks into which the array A can be divided.
25 | Array A can be divided into blocks as follows:
26 | one block (1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2). This block contains three peaks.
27 | two blocks (1, 2, 3, 4, 3, 4) and (1, 2, 3, 4, 6, 2). Every block has a peak.
28 | three blocks (1, 2, 3, 4), (3, 4, 1, 2), (3, 4, 6, 2). Every block has a peak. Notice in particular that the first block (1, 2, 3, 4) has a peak at A[3], because A[2] < A[3] > A[4], even though A[4] is in the adjacent block.
29 | However, array A cannot be divided into four blocks, (1, 2, 3), (4, 3, 4), (1, 2, 3) and (4, 6, 2), because the (1, 2, 3) blocks do not contain a peak. Notice in particular that the (4, 3, 4) block contains two peaks: A[3] and A[5].
30 | The maximum number of blocks that array A can be divided into is three.
31 | Write a function:
32 | class Solution { public int solution(int[] A); }
33 | that, given a non-empty zero-indexed array A consisting of N integers, returns the maximum number of blocks into which A can be divided.
34 | If A cannot be divided into some number of blocks, the function should return 0.
35 | For example, given:
36 | A[0] = 1
37 | A[1] = 2
38 | A[2] = 3
39 | A[3] = 4
40 | A[4] = 3
41 | A[5] = 4
42 | A[6] = 1
43 | A[7] = 2
44 | A[8] = 3
45 | A[9] = 4
46 | A[10] = 6
47 | A[11] = 2
48 | the function should return 3, as explained above.
49 | Assume that:
50 | N is an integer within the range [1..100,000];
51 | each element of array A is an integer within the range [0..1,000,000,000].
52 | Complexity:
53 | expected worst-case time complexity is O(N*log(log(N)));
54 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
55 | Elements of input arrays can be modified.
56 | */
57 |
58 | //Score: 100/100
59 |
60 | package primeandcompositenumbers;
61 |
62 | import java.util.ArrayList;
63 |
64 | public class Peaks {
65 |
66 | public static void main(String[] args) {
67 | int[] N = new int[] {1,2,3,4,3,4,1,2,3,4,6,2};
68 | System.out.println(solution(N));
69 | }
70 |
71 | public static int solution(int[] A) {
72 | int peakCount = 0;
73 | ArrayList peaks = new ArrayList();
74 | for (int i = 1; i < A.length-1; i++) {
75 | if (A[i]>A[i-1] && A[i]>A[i+1]) {
76 | peaks.add(i);
77 | peakCount++;
78 | }
79 | }
80 | for (int size = 1; size <=A.length; size++) {
81 | int blocks = A.length/size;
82 | if (A.length % size != 0 || blocks>peakCount)
83 | continue;
84 |
85 | boolean ok = true;
86 | int threshold = 0;
87 | for (int j = 0; j < peaks.size(); j++) {
88 | if(peaks.get(j) / size > threshold) {
89 | ok = false;
90 | break;
91 | }
92 | if (peaks.get(j)/size == threshold)
93 | threshold++;
94 | }
95 |
96 | if (threshold != blocks)
97 | ok= false;
98 | if(ok)
99 | return blocks;
100 | }
101 | return 0;
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/src/sieveoferastothenes/CountNonDivisible.java:
--------------------------------------------------------------------------------
1 | /*
2 | You are given a non-empty zero-indexed array A consisting of N integers.
3 | For each number A[i] such that 0 ≤ i < N, we want to count the number of elements of the array that are not the divisors of A[i]. We say that these elements are non-divisors.
4 | For example, consider integer N = 5 and array A such that:
5 | A[0] = 3
6 | A[1] = 1
7 | A[2] = 2
8 | A[3] = 3
9 | A[4] = 6
10 | For the following elements:
11 | A[0] = 3, the non-divisors are: 2, 6,
12 | A[1] = 1, the non-divisors are: 3, 2, 3, 6,
13 | A[2] = 2, the non-divisors are: 3, 3, 6,
14 | A[3] = 3, the non-divisors are: 2, 6,
15 | A[6] = 6, there aren't any non-divisors.
16 | Write a function:
17 | class Solution { public int[] solution(int[] A); }
18 | that, given a non-empty zero-indexed array A consisting of N integers, returns a sequence of integers representing the amount of non-divisors.
19 | The sequence should be returned as:
20 | a structure Results (in C), or
21 | a vector of integers (in C++), or
22 | a record Results (in Pascal), or
23 | an array of integers (in any other programming language).
24 | For example, given:
25 | A[0] = 3
26 | A[1] = 1
27 | A[2] = 2
28 | A[3] = 3
29 | A[4] = 6
30 | the function should return [2, 4, 3, 2, 0], as explained above.
31 | Assume that:
32 | N is an integer within the range [1..50,000];
33 | each element of array A is an integer within the range [1..2 * N].
34 | Complexity:
35 | expected worst-case time complexity is O(N*log(N));
36 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
37 | Elements of input arrays can be modified.
38 | */
39 |
40 | //SCORE: 100/100
41 | package sieveoferastothenes;
42 |
43 | import java.util.Arrays;
44 |
45 | public class CountNonDivisible {
46 |
47 | public static void main (String[] args) {
48 | int[] A = new int[] {3,1,2,3,6};
49 | System.out.println(Arrays.toString(solution(A)));
50 | }
51 |
52 | public static int[] solution(int[] A) {
53 | int[][] D = new int[2*A.length + 1][2];
54 | int[] res = new int[A.length];
55 | for (int i = 0; i < A.length; i++) {
56 | D[A[i]][0]++;
57 | D[A[i]][1] = -1;
58 | }
59 | for (int i = 0; i < A.length; i++) {
60 | if(D[A[i]][1]==-1) {
61 | D[A[i]][1]=0;
62 | for (int j = 1; j*j <= A[i]; j++) {
63 | if(A[i] % j == 0) {
64 | D[A[i]][1]+= D[j][0];
65 | if (A[i]/j != j)
66 | D[A[i]][1]+= D[A[i]/j][0];
67 | }
68 |
69 | }
70 | }
71 | }
72 | for (int i = 0; i < A.length; i++) {
73 | res[i] = A.length - D[A[i]][1];
74 | }
75 | return res;
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/sieveoferastothenes/CountSemiprimes.java:
--------------------------------------------------------------------------------
1 | /*
2 | A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13.
3 | A semiprime is a natural number that is the product of two (not necessarily distinct) prime numbers. The first few semiprimes are 4, 6, 9, 10, 14, 15, 21, 22, 25, 26.
4 | You are given two non-empty zero-indexed arrays P and Q, each consisting of M integers. These arrays represent queries about the number of semiprimes within specified ranges.
5 | Query K requires you to find the number of semiprimes within the range (P[K], Q[K]), where 1 ≤ P[K] ≤ Q[K] ≤ N.
6 | For example, consider an integer N = 26 and arrays P, Q such that:
7 | P[0] = 1 Q[0] = 26
8 | P[1] = 4 Q[1] = 10
9 | P[2] = 16 Q[2] = 20
10 | The number of semiprimes within each of these ranges is as follows:
11 | (1, 26) is 10,
12 | (4, 10) is 4,
13 | (16, 20) is 0.
14 | Write a function:
15 | class Solution { public int[] solution(int N, int[] P, int[] Q); }
16 | that, given an integer N and two non-empty zero-indexed arrays P and Q consisting of M integers, returns an array consisting of M elements specifying the consecutive answers to all the queries.
17 | For example, given an integer N = 26 and arrays P, Q such that:
18 | P[0] = 1 Q[0] = 26
19 | P[1] = 4 Q[1] = 10
20 | P[2] = 16 Q[2] = 20
21 | the function should return the values [10, 4, 0], as explained above.
22 | Assume that:
23 | N is an integer within the range [1..50,000];
24 | M is an integer within the range [1..30,000];
25 | each element of arrays P, Q is an integer within the range [1..N];
26 | P[i] ≤ Q[i].
27 | Complexity:
28 | expected worst-case time complexity is O(N*log(log(N))+M);
29 | expected worst-case space complexity is O(N+M), beyond input storage (not counting the storage required for input arguments).
30 | Elements of input arrays can be modified.
31 | */
32 |
33 | //Score: 100/100
34 | package sieveoferastothenes;
35 |
36 | import java.util.Arrays;
37 |
38 | public class CountSemiprimes {
39 |
40 | public static void main (String[] args) {
41 | int[] A = new int[] {1,4,16};
42 | int[] B = new int[]{26,10,20};
43 | int N = 26;
44 | System.out.println(Arrays.toString(solution(A,B,N)));
45 |
46 | }
47 |
48 | public static int[] solution(int[] A, int[] B, int N) {
49 | int[] factArray = factorizationArray(N);
50 | int[] semiPrimes = new int[factArray.length];
51 | for (int i = 0; i < semiPrimes.length; i++) {
52 | if (factArray[i] != 0 && factArray[i/factArray[i]] == 0)
53 | semiPrimes[i] = 1;
54 | }
55 | int[] semiPrimesPreSum = prefixSum(semiPrimes);
56 | int[] res = new int[A.length];
57 | for (int i = 0; i < B.length; i++) {
58 | res[i] = semiPrimesPreSum[B[i]] - semiPrimesPreSum[A[i]-1];
59 | }
60 | return res;
61 | }
62 |
63 | //preparing array for factorization (array with primes)
64 | public static int[] factorizationArray(int n) {
65 | int[] F = new int[n+1];
66 | for (int i = 2; i*i <= n; i++) {
67 | if (F[i] == 0) {
68 | for (int k = i*i; k<=n; k+=i) {
69 | if (F[k] == 0)
70 | F[k] = i;
71 | }
72 | }
73 | }
74 | return F;
75 | }
76 | public static int[] prefixSum(int[] A) {
77 | int[] prefSum = new int[A.length];
78 | for (int i = 0; i < A.length; i++) {
79 | if (i==0)
80 | prefSum[i] = A[i];
81 | else
82 | prefSum[i] = prefSum[i-1] + A[i];
83 | }
84 | return prefSum;
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/sorting/Distinct.java:
--------------------------------------------------------------------------------
1 | /*
2 | Write a function
3 | class Solution { public int solution(int[] A); }
4 | that, given a zero-indexed array A consisting of N integers, returns the number of distinct values in array A.
5 | Assume that:
6 | N is an integer within the range [0..100,000];
7 | each element of array A is an integer within the range [−1,000,000..1,000,000].
8 | For example, given array A consisting of six elements such that:
9 | A[0] = 2 A[1] = 1 A[2] = 1
10 | A[3] = 2 A[4] = 3 A[5] = 1
11 | the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.
12 | Complexity:
13 | expected worst-case time complexity is O(N*log(N));
14 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
15 | Elements of input arrays can be modified.
16 | */
17 |
18 | //SCORE:100/100
19 | package sorting;
20 |
21 | import java.util.Arrays;
22 |
23 | public class Distinct {
24 | public static void main (String[] args) {
25 | int[] A = new int[] {2,1,1,2,3,1};
26 | System.out.println(solution(A));
27 | }
28 |
29 | public static int solution(int[] A) {
30 | Arrays.sort(A);
31 | int dupl=0;
32 | for (int i = 1; i < A.length; i++) {
33 | if (A[i] == A[i-1])
34 | dupl++;
35 | }
36 | return A.length - dupl;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/sorting/MaxProductOfThree.java:
--------------------------------------------------------------------------------
1 | /*
2 | 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).
3 | For example, array A such that:
4 | A[0] = -3
5 | A[1] = 1
6 | A[2] = 2
7 | A[3] = -2
8 | A[4] = 5
9 | A[5] = 6
10 | contains the following example triplets:
11 | (0, 1, 2), product is −3 * 1 * 2 = −6
12 | (1, 2, 4), product is 1 * 2 * 5 = 10
13 | (2, 4, 5), product is 2 * 5 * 6 = 60
14 | Your goal is to find the maximal product of any triplet.
15 | Write a function:
16 | class Solution { public int solution(int[] A); }
17 | that, given a non-empty zero-indexed array A, returns the value of the maximal product of any triplet.
18 | For example, given array A such that:
19 | A[0] = -3
20 | A[1] = 1
21 | A[2] = 2
22 | A[3] = -2
23 | A[4] = 5
24 | A[5] = 6
25 | the function should return 60, as the product of triplet (2, 4, 5) is maximal.
26 | Assume that:
27 | N is an integer within the range [3..100,000];
28 | each element of array A is an integer within the range [−1,000..1,000].
29 | Complexity:
30 | expected worst-case time complexity is O(N*log(N));
31 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
32 | Elements of input arrays can be modified.
33 | */
34 |
35 | //SCORE: 100/100
36 | package sorting;
37 |
38 | import java.util.Arrays;
39 |
40 | public class MaxProductOfThree {
41 | public static void main (String[] args) {
42 | int[] A = new int[] {-3,1,2,-2,5,6};
43 | System.out.println(solution(A));
44 | }
45 |
46 | public static int solution(int[] A) {
47 | Arrays.sort(A);
48 | System.out.println(Arrays.toString(A));
49 | int max1 = A[A.length-1] *A[A.length-2] *A[A.length-3];
50 | int max2 = A[A.length-1] *A[0] *A[1];
51 | return max1>max2?max1:max2;
52 | }
53 | }
54 |
55 |
--------------------------------------------------------------------------------
/src/sorting/NumberOfDiscIntersection.java:
--------------------------------------------------------------------------------
1 | /*
2 | Given an array A of N integers, we draw N discs in a 2D plane such that the I-th disc is centered on (0,I) and has a radius of A[I]. We say that the J-th disc and K-th disc intersect if J ≠ K and J-th and K-th discs have at least one common point.
3 | Write a function:
4 | int solution(int A[], int N);
5 | that, given an array A describing N discs as explained above, returns the number of pairs of intersecting discs. For example, given N=6 and:
6 | A[0] = 1 A[1] = 5 A[2] = 2
7 | A[3] = 1 A[4] = 4 A[5] = 0
8 | intersecting discs appear in eleven pairs of elements:
9 | 0 and 1,
10 | 0 and 2,
11 | 0 and 4,
12 | 1 and 2,
13 | 1 and 3,
14 | 1 and 4,
15 | 1 and 5,
16 | 2 and 3,
17 | 2 and 4,
18 | 3 and 4,
19 | 4 and 5.
20 | so the function should return 11.
21 | The function should return −1 if the number of intersecting pairs exceeds 10,000,000.
22 | Assume that:
23 | N is an integer within the range [0..100,000];
24 | each element of array A is an integer within the range [0..2147483647].
25 | Complexity:
26 | expected worst-case time complexity is O(N*log(N));
27 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
28 | Elements of input arrays can be modified.
29 | */
30 |
31 | //SCORE: 100/62
32 | package sorting;
33 |
34 | public class NumberOfDiscIntersection {
35 | public static void main (String[] args) {
36 | int[] A = new int[] {1, 5, 2, 1, 4, 0};
37 | System.out.println(solution(A));
38 | }
39 |
40 | public static int solution(int[] A) {
41 | int x = 0;
42 | for (int i = 0; i < A.length-1; i++) {
43 | for (int j = i+1; j < A.length; j++) {
44 | if ((long)A[i]+i >= j - (long)A[j]) {
45 | x++;
46 | if (x>10000000)
47 | return -1;
48 | }
49 | }
50 | }
51 | return x;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/sorting/Triangle.java:
--------------------------------------------------------------------------------
1 | /*
2 | 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:
3 | A[P] + A[Q] > A[R],
4 | A[Q] + A[R] > A[P],
5 | A[R] + A[P] > A[Q].
6 | For example, consider array A such that:
7 | A[0] = 10 A[1] = 2 A[2] = 5
8 | A[3] = 1 A[4] = 8 A[5] = 20
9 | Triplet (0, 2, 4) is triangular.
10 | Write a function:
11 | class Solution { public int solution(int[] A); }
12 | 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. For example, given array A such that:
13 | A[0] = 10 A[1] = 2 A[2] = 5
14 | A[3] = 1 A[4] = 8 A[5] = 20
15 | the function should return 1, as explained above. Given array A such that:
16 | A[0] = 10 A[1] = 50 A[2] = 5
17 | A[3] = 1
18 | the function should return 0.
19 | Assume that:
20 | N is an integer within the range [0..1,000,000];
21 | each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
22 | Complexity:
23 | expected worst-case time complexity is O(N*log(N));
24 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
25 | Elements of input arrays can be modified.
26 | */
27 |
28 | //SCORE: 100/100
29 | package sorting;
30 |
31 | import java.util.Arrays;
32 |
33 | public class Triangle {
34 | public static void main (String[] args) {
35 | int[] A = new int[] {10,2,5,1,8,20};
36 | System.out.println(solution(A));
37 | }
38 |
39 | public static int solution(int[] A) {
40 | if (A.length < 3)
41 | return 0;
42 | Arrays.sort(A);
43 | for (int i = 2; i < A.length; i++) {
44 | if ((long)A[i-2] + (long)A[i-1] > (long)A[i])
45 | return 1;
46 | }
47 | return 0;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/stackandqueue/Brackets.java:
--------------------------------------------------------------------------------
1 | /*
2 | A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:
3 | S is empty;
4 | S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
5 | S has the form "VW" where V and W are properly nested strings.
6 | For example, the string "{[()()]}" is properly nested but "([)()]" is not.
7 | Write a function:
8 | class Solution { public int solution(String S); }
9 | that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.
10 | For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above.
11 | Assume that:
12 | N is an integer within the range [0..200,000];
13 | string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".
14 | Complexity:
15 | expected worst-case time complexity is O(N);
16 | expected worst-case space complexity is O(N) (not counting the storage required for input arguments).
17 | */
18 |
19 | //SCORE:100/100
20 | package stackandqueue;
21 |
22 | import java.util.Stack;
23 |
24 | public class Brackets {
25 | public static void main (String[] args) {
26 | String S= "{[()()]}";
27 | System.out.println(solution(S));
28 | }
29 |
30 | public static int solution(String S) {
31 | Stack chars = new Stack();
32 | for (int i = 0; i < S.length(); i++) {
33 | if (chars.size() == 0)
34 | chars.push(S.charAt(i));
35 | else {
36 | if (isMatch(chars.peek(), S.charAt(i)))
37 | chars.pop();
38 | else
39 | chars.push(S.charAt(i));
40 | }
41 | }
42 | return chars.size()==0?1:0;
43 | }
44 |
45 | private static boolean isMatch(char a, char b) {
46 | switch(a) {
47 | case '{': return b == '}';
48 | case '(': return b == ')';
49 | case '[': return b == ']';
50 | default: return false;
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/stackandqueue/Fish.java:
--------------------------------------------------------------------------------
1 | /*
2 | You are given two non-empty zero-indexed arrays A and B consisting of N integers. Arrays A and B represent N voracious fish in a river, ordered downstream along the flow of the river.
3 | The fish are numbered from 0 to N − 1. If P and Q are two fish and P < Q, then fish P is initially upstream of fish Q. Initially, each fish has a unique position.
4 | Fish number P is represented by A[P] and B[P]. Array A contains the sizes of the fish. All its elements are unique. Array B contains the directions of the fish. It contains only 0s and/or 1s, where:
5 | 0 represents a fish flowing upstream,
6 | 1 represents a fish flowing downstream.
7 | If two fish move in opposite directions and there are no other (living) fish between them, they will eventually meet each other. Then only one fish can stay alive − the larger fish eats the smaller one. More precisely, we say that two fish P and Q meet each other when P < Q, B[P] = 1 and B[Q] = 0, and there are no living fish between them. After they meet:
8 | If A[P] > A[Q] then P eats Q, and P will still be flowing downstream,
9 | If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream.
10 | We assume that all the fish are flowing at the same speed. That is, fish moving in the same direction never meet. The goal is to calculate the number of fish that will stay alive.
11 | For example, consider arrays A and B such that:
12 | A[0] = 4 B[0] = 0
13 | A[1] = 3 B[1] = 1
14 | A[2] = 2 B[2] = 0
15 | A[3] = 1 B[3] = 0
16 | A[4] = 5 B[4] = 0
17 | Initially all the fish are alive and all except fish number 1 are moving upstream. Fish number 1 meets fish number 2 and eats it, then it meets fish number 3 and eats it too. Finally, it meets fish number 4 and is eaten by it. The remaining two fish, number 0 and 4, never meet and therefore stay alive.
18 | Write a function:
19 | class Solution { public int solution(int[] A, int[] B); }
20 | that, given two non-empty zero-indexed arrays A and B consisting of N integers, returns the number of fish that will stay alive.
21 | For example, given the arrays shown above, the function should return 2, as explained above.
22 | Assume that:
23 | N is an integer within the range [1..100,000];
24 | each element of array A is an integer within the range [0..1,000,000,000];
25 | each element of array B is an integer that can have one of the following values: 0, 1;
26 | the elements of A are all distinct.
27 | Complexity:
28 | expected worst-case time complexity is O(N);
29 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
30 | Elements of input arrays can be modified.
31 | */
32 |
33 | //SCORE: 100/100
34 | package stackandqueue;
35 |
36 | import java.util.Stack;
37 |
38 | public class Fish {
39 |
40 | public static void main (String[] args) {
41 | int[] A = new int[]{4,3,2,1,5};
42 | int[] B = new int[]{0,1,0,0,0};
43 | System.out.println(solution(A,B));
44 | }
45 |
46 | public static int solution(int[] A, int[] B) {
47 | Stack stack = new Stack();
48 | int duels = 0;
49 | for (int i = 0; i < A.length; i++) {
50 | if (B[i] == 0) {
51 | while(!stack.isEmpty()) {
52 | duels++;
53 | if (A[i] < A[stack.peek()])
54 | break;
55 | stack.pop();
56 | }
57 | }
58 | else
59 | stack.push(B[i]);
60 | }
61 | return A.length - duels;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/stackandqueue/Nesting.java:
--------------------------------------------------------------------------------
1 | /*
2 | A string S consisting of N characters is called properly nested if:
3 | S is empty;
4 | S has the form "(U)" where U is a properly nested string;
5 | S has the form "VW" where V and W are properly nested strings.
6 | For example, string "(()(())())" is properly nested but string "())" isn't.
7 | Write a function:
8 | class Solution { public int solution(String S); }
9 | that, given a string S consisting of N characters, returns 1 if string S is properly nested and 0 otherwise.
10 | For example, given S = "(()(())())", the function should return 1 and given S = "())", the function should return 0, as explained above.
11 | Assume that:
12 | N is an integer within the range [0..1,000,000];
13 | string S consists only of the characters "(" and/or ")".
14 | Complexity:
15 | expected worst-case time complexity is O(N);
16 | expected worst-case space complexity is O(1) (not counting the storage required for input arguments).
17 | */
18 |
19 | //SCORE: 100/100
20 | package stackandqueue;
21 |
22 | import java.util.Stack;
23 |
24 | public class Nesting {
25 |
26 | public static void main (String[] args) {
27 | String S= "((()()))";
28 | System.out.println(solution(S));
29 | }
30 |
31 | public static int solution(String S) {
32 | Stack chars = new Stack();
33 | for (int i = 0; i < S.length(); i++) {
34 | if (S.charAt(i) == '(') {
35 | chars.push(S.charAt(i));
36 | } else if (S.charAt(i) == ')' && chars.size()>0) {
37 | chars.pop();
38 | } else return 0;
39 | }
40 | return chars.size()==0?1:0;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/stackandqueue/StoneWall.java:
--------------------------------------------------------------------------------
1 | /*
2 | 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 a zero-indexed 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.
3 | 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.
4 | Write a function:
5 | class Solution { public int solution(int[] H); }
6 | that, given a zero-indexed array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it.
7 | For example, given array H containing N = 9 integers:
8 | H[0] = 8 H[1] = 8 H[2] = 5
9 | H[3] = 7 H[4] = 9 H[5] = 8
10 | H[6] = 7 H[7] = 4 H[8] = 8
11 | the function should return 7. The figure shows one possible arrangement of seven blocks.
12 |
13 | Assume that:
14 | N is an integer within the range [1..100,000];
15 | each element of array H is an integer within the range [1..1,000,000,000].
16 | Complexity:
17 | expected worst-case time complexity is O(N);
18 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
19 | Elements of input arrays can be modified.
20 | */
21 |
22 | //SCORE: 100/100
23 | package stackandqueue;
24 |
25 | import java.util.Stack;
26 |
27 | public class StoneWall {
28 |
29 | public static void main (String[] args) {
30 | int[] A = new int[]{8,8,5,7,9,8,7,4,8};
31 | System.out.println(solution(A));
32 | }
33 |
34 | public static int solution(int[] H) {
35 | Stack stack = new Stack();
36 | int blocks = 1;
37 | stack.push(H[0]);
38 | for (int i = 1; i < H.length; i++) {
39 | if (stack.peek() == H[i])
40 | continue;
41 | else if (H[i] > stack.peek()) {
42 | stack.push(H[i]);
43 | blocks++;
44 | } else {
45 | while(stack.size()>0 && stack.peek()>H[i])
46 | stack.pop();
47 | if (stack.size() == 0 || stack.peek() != H[i]) {
48 | stack.push(H[i]);
49 | blocks++;
50 | }
51 | }
52 | }
53 | return blocks;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/timecomplexity/FrogJump.java:
--------------------------------------------------------------------------------
1 | /*
2 | 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.
3 | Count the minimal number of jumps that the small frog must perform to reach its target.
4 | Write a function:
5 | class Solution { public int solution(int X, int Y, int D); }
6 | 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.
7 | For example, given:
8 | X = 10
9 | Y = 85
10 | D = 30
11 | the function should return 3, because the frog will be positioned as follows:
12 | after the first jump, at position 10 + 30 = 40
13 | after the second jump, at position 10 + 30 + 30 = 70
14 | after the third jump, at position 10 + 30 + 30 + 30 = 100
15 | Assume that:
16 | X, Y and D are integers within the range [1..1,000,000,000];
17 | X ≤ Y.
18 | Complexity:
19 | expected worst-case time complexity is O(1);
20 | expected worst-case space complexity is O(1).
21 | */
22 |
23 | //SCORE: 100/100
24 | package timecomplexity;
25 |
26 | public class FrogJump {
27 |
28 | public static void main(String[] args) {
29 | int A = 10;
30 | int B = 85;
31 | int D = 30;
32 | System.out.println(solution(A,B, D));
33 | }
34 |
35 | public static int solution(int x, int y, int d) {
36 | return (int)Math.ceil((double)(y-x)/d);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/timecomplexity/PermMissingElements.java:
--------------------------------------------------------------------------------
1 | /*
2 | 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.
3 | Your goal is to find that missing element.
4 | Write a function:
5 | class Solution { public int solution(int[] A); }
6 | that, given a zero-indexed array A, returns the value of the missing element.
7 | For example, given array A such that:
8 | A[0] = 2
9 | A[1] = 3
10 | A[2] = 1
11 | A[3] = 5
12 | the function should return 4, as it is the missing element.
13 | Assume that:
14 | N is an integer within the range [0..100,000];
15 | the elements of A are all distinct;
16 | each element of array A is an integer within the range [1..(N + 1)].
17 | Complexity:
18 | expected worst-case time complexity is O(N);
19 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
20 | Elements of input arrays can be modified.
21 | */
22 |
23 | //SCORE: 100/100
24 | package timecomplexity;
25 |
26 | public class PermMissingElements {
27 |
28 | public static void main(String[] args) {
29 | int[] A = new int[]{2,3,1,5};
30 | System.out.println(solution(A));
31 | }
32 |
33 | public static int solution(int[] A) {
34 | int[] counters = new int[A.length+2];
35 | for (int i = 0; i < A.length; i++) {
36 | counters[A[i]] = 1;
37 | }
38 | for (int i = 1; i < counters.length; i++) {
39 | if (counters[i] == 0)
40 | return i;
41 | }
42 | //no element is missing
43 | return -1;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/timecomplexity/TapeEquilibrium.java:
--------------------------------------------------------------------------------
1 | /*
2 | A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape.
3 | 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].
4 | 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])|
5 | In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
6 | For example, consider array A such that:
7 | A[0] = 3
8 | A[1] = 1
9 | A[2] = 2
10 | A[3] = 4
11 | A[4] = 3
12 | We can split this tape in four places:
13 | P = 1, difference = |3 − 10| = 7
14 | P = 2, difference = |4 − 9| = 5
15 | P = 3, difference = |6 − 7| = 1
16 | P = 4, difference = |10 − 3| = 7
17 | Write a function:
18 | class Solution { public int solution(int[] A); }
19 | that, given a non-empty zero-indexed array A of N integers, returns the minimal difference that can be achieved.
20 | For example, given:
21 | A[0] = 3
22 | A[1] = 1
23 | A[2] = 2
24 | A[3] = 4
25 | A[4] = 3
26 | the function should return 1, as explained above.
27 | Assume that:
28 | N is an integer within the range [2..100,000];
29 | each element of array A is an integer within the range [−1,000..1,000].
30 | Complexity:
31 | expected worst-case time complexity is O(N);
32 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
33 | Elements of input arrays can be modified.
34 | */
35 |
36 | //SCORE: 100/100
37 | package timecomplexity;
38 |
39 | public class TapeEquilibrium {
40 |
41 | public static void main(String[] args) {
42 | int[] A = new int[]{3,1,2,4,3};
43 | System.out.println(solution(A));
44 | }
45 |
46 | public static int solution(int[] A) {
47 | int res = Integer.MAX_VALUE;
48 | int tmp=0;
49 | int sum = 0;
50 | for (int i = 0; i < A.length; i++) {
51 | sum += A[i];
52 | }
53 | for (int i = 0; i < A.length-1; i++) {
54 | tmp+=A[i];
55 | res = Math.min(res, Math.abs(tmp - (sum - tmp)));
56 | }
57 | return res;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------