├── .gitignore ├── LICENSE ├── README.md └── src └── main └── java └── com └── cutajarjames └── codility ├── arrays └── CyclicRotation.java ├── caterpillarmethod ├── CountDistinctSlices.java └── MinAbsSumOfTwo.java ├── countingelements ├── FrogRiverOne.java ├── MaxCounters.java └── MissingInteger.java ├── euclidean └── ChocolatesByNumbers.java ├── greedy ├── MaxNonOverlappingSegments.java └── TieRopes.java ├── leader └── Dominator.java ├── maximumsliceproblem └── MaxProfit.java ├── prefixsums ├── CountDiv.java ├── PassingCars.java └── countdivconsole.txt ├── primeandcompositenumbers ├── Flags.java └── FlagsFaster.java ├── sorting ├── NumberOfDiscIntersections.java └── NumberOfDiscIntersectionsAlt.java ├── stacksandqueues ├── Brackets.java └── Fish.java └── timecomplexity ├── PermMissingElem.java └── TapeEquilibrium.java /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | .idea/ 3 | 4 | # Compiled class file 5 | *.class 6 | 7 | # Log file 8 | *.log 9 | 10 | # BlueJ files 11 | *.ctxt 12 | 13 | # Mobile Tools for Java (J2ME) 14 | .mtj.tmp/ 15 | 16 | # Package Files # 17 | *.jar 18 | *.war 19 | *.nar 20 | *.ear 21 | *.zip 22 | *.tar.gz 23 | *.rar 24 | 25 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 26 | hs_err_pid* 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 James Cutajar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CodilityInJava 2 | Solutions to Codility's puzzles in Java 3 | The udemy course for this repo can be found at: 4 | 5 | https://www.udemy.com/beat-the-codility-coding-interview-in-java/?couponCode=3E8YU5Z 6 | 7 | All of these can be tested at: 8 | https://codility.com/programmers/lessons/ 9 | 10 | Please do get in touch if you find any suggestions or improvements! 11 | 12 | Follow me on https://twitter.com/cutajarj 13 | 14 | And checkout my blog at: www.cutajarjames.com 15 | 16 | yes, there is a bug in this readme: 17 | ``` 18 | .--. .--. 19 | _ ` \ / ` _ 20 | `\.===. \.^./ .===./` 21 | \/`"`\/ 22 | , | | , 23 | / `\|`-.-'|/` \ 24 | / | \ | \ 25 | .-' ,-'`| ; |`'-, '-. 26 | | | \| | 27 | | | ;| | 28 | | \ // | 29 | | `._//' | 30 | jgs .' `. 31 | _,' `,_ 32 | 33 | ``` -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/arrays/CyclicRotation.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.arrays; 2 | 3 | 4 | import java.util.Arrays; 5 | 6 | /** 7 | * This is the solution for Arrays > CyclicRotation 8 | *

9 | * This is marked as PAINLESS difficulty 10 | */ 11 | public class CyclicRotation { 12 | 13 | public int[] solution(int[] A, int K) { 14 | int[] result = new int[A.length]; 15 | for (int i = 0; i < result.length; i++) { 16 | result[(i + K) % A.length] = A[i]; 17 | } 18 | 19 | return result; 20 | } 21 | 22 | public static void main(String[] args) { 23 | System.out.println(Arrays.toString(new CyclicRotation().solution(new int[]{7, 2, 8, 3, 5}, 2))); 24 | 25 | System.out.println(Arrays.toString(new CyclicRotation().solution(new int[]{7, 2, 8, 3, 5}, 5))); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/caterpillarmethod/CountDistinctSlices.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.caterpillarmethod; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * This is the solution for Caterpillar method > CountDistinctSlices 7 | * 8 | * This is marked as PAINLESS difficulty 9 | */ 10 | 11 | public class CountDistinctSlices { 12 | public int solution(int M, int[] A) { 13 | int totalSlices = 0; 14 | boolean[] inCurrentSlice = new boolean[M + 1]; 15 | Arrays.fill(inCurrentSlice, false); 16 | int head = 0; 17 | for (int tail = 0; tail < A.length; tail++) { 18 | while (head < A.length && !inCurrentSlice[A[head]]) { 19 | inCurrentSlice[A[head]] = true; 20 | totalSlices += (head - tail) + 1; 21 | head += 1; 22 | if (totalSlices > 1000000000) 23 | totalSlices = 1000000000; 24 | } 25 | inCurrentSlice[A[tail]] = false; 26 | } 27 | return totalSlices; 28 | } 29 | 30 | public static void main(String[] args) { 31 | System.out.println(new CountDistinctSlices().solution(9, new int[]{2, 4, 1, 7, 4, 9, 7, 3, 5, 5, 8, 7, 1})); 32 | System.out.println(new CountDistinctSlices().solution(6, new int[]{3, 4, 5, 5, 2})); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/caterpillarmethod/MinAbsSumOfTwo.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.caterpillarmethod; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * This is the solution for Caterpillar method > MinAbsSumOfTwo 7 | * 8 | * This is marked as RESPECTABLE difficulty 9 | */ 10 | 11 | public class MinAbsSumOfTwo { 12 | public int solution(int[] A) { 13 | int minAbsSumOfTwo = Integer.MAX_VALUE; 14 | Arrays.sort(A); 15 | int head = 0; 16 | int tail = A.length - 1; 17 | while (head <= tail) { 18 | minAbsSumOfTwo = Math.min(minAbsSumOfTwo, Math.abs(A[head] + A[tail])); 19 | if (A[head] + A[tail] < 0) head++; 20 | else tail--; 21 | } 22 | return minAbsSumOfTwo; 23 | } 24 | 25 | public static void main(String[] args) { 26 | System.out.println(new MinAbsSumOfTwo().solution(new int[]{-7, 3, -1, 5, -11, 4, -9, 14, 17, -2})); //1 27 | System.out.println(new MinAbsSumOfTwo().solution(new int[]{8, 3, 5, 16, 11})); //6 28 | System.out.println(new MinAbsSumOfTwo().solution(new int[]{-7, -5, -6, -2, -9})); //4 29 | System.out.println(new MinAbsSumOfTwo().solution(new int[]{-7, 3, -6, 1, 0, -9})); //0 30 | System.out.println(new MinAbsSumOfTwo().solution(new int[]{-22, 3, 4, 5})); //6 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/countingelements/FrogRiverOne.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.countingelements; 2 | 3 | /** 4 | * This is the solution for CountingElements > FrogRiverOne 5 | *

6 | * This is marked as PAINLESS difficulty 7 | */ 8 | public class FrogRiverOne { 9 | public int solution(int X, int[] A) { 10 | boolean[] riverPositions = new boolean[X + 1]; 11 | for (int time = 0; time < A.length; time++) { 12 | int pos = A[time]; 13 | if (!riverPositions[pos]) { 14 | riverPositions[pos] = true; 15 | X -= 1; 16 | if (X == 0) return time; 17 | } 18 | } 19 | return -1; 20 | } 21 | 22 | public static void main(String[] args) { 23 | System.out.println(new FrogRiverOne().solution(5, new int[]{1, 3, 1, 4, 2, 3, 5, 4})); 24 | System.out.println(new FrogRiverOne().solution(1, new int[]{1, 1, 1})); 25 | System.out.println(new FrogRiverOne().solution(3, new int[]{1, 2, 1})); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/countingelements/MaxCounters.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.countingelements; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * This is the solution for CountingElements > MaxCounters 7 | *

8 | * This is marked as RESPECTABLE difficulty 9 | */ 10 | public class MaxCounters { 11 | public int[] solution(int N, int[] A) { 12 | int[] counters = new int[N]; 13 | Arrays.fill(counters, 0); 14 | int start_line = 0; 15 | int current_max = 0; 16 | for (int i : A) { 17 | int x = i - 1; 18 | if (i > N) start_line = current_max; 19 | else if (counters[x] < start_line) counters[x] = start_line + 1; 20 | else counters[x] += 1; 21 | if (i <= N && counters[x] > current_max) current_max = counters[x]; 22 | } 23 | for (int i = 0; i < counters.length; i++) 24 | if (counters[i] < start_line) counters[i] = start_line; 25 | return counters; 26 | } 27 | 28 | public static void main(String[] args) { 29 | System.out.println(Arrays.toString(new MaxCounters().solution(5, new int[]{3, 4, 4, 6, 1, 4, 4}))); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/countingelements/MissingInteger.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.countingelements; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * This is the solution for CountingElements > MissingInteger 7 | *

8 | * This is marked as RESPECTABLE difficulty 9 | */ 10 | public class MissingInteger { 11 | public int solution(int[] A) { 12 | boolean[] presentMarkers = new boolean[A.length + 2]; 13 | Arrays.fill(presentMarkers, false); 14 | for (int i : A) { 15 | if (i > 0 && i <= A.length) presentMarkers[i] = true; 16 | } 17 | int missingCandidate = 1; 18 | while (presentMarkers[missingCandidate]) { 19 | missingCandidate ++; 20 | } 21 | return missingCandidate; 22 | } 23 | 24 | public static void main(String[] args) { 25 | System.out.println(new MissingInteger().solution(new int[]{1,3,6,4,1,2})); 26 | System.out.println(new MissingInteger().solution(new int[]{1,1,1,9,9,9})); 27 | System.out.println(new MissingInteger().solution(new int[]{1, 2, 3})); 28 | System.out.println(new MissingInteger().solution(new int[]{-1, -3})); 29 | System.out.println(new MissingInteger().solution(new int[]{-1, -3, 1})); 30 | System.out.println(new MissingInteger().solution(new int[]{-1, -3, 3})); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/euclidean/ChocolatesByNumbers.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.euclidean; 2 | 3 | /** 4 | * This is the solution for Euclidean Algorithms > ChocolatesByNumbers 5 | *

6 | * This is marked as PAINLESS difficulty 7 | */ 8 | public class ChocolatesByNumbers { 9 | private int findGcd(int a, int b) { 10 | if (b == 0) 11 | return a; 12 | else 13 | return findGcd(b, a % b); 14 | } 15 | 16 | public int solution(int N, int M) { 17 | return N / findGcd(N, M); 18 | } 19 | 20 | public static void main(String[] args) { 21 | System.out.println(new ChocolatesByNumbers().solution(10,4)); 22 | System.out.println(new ChocolatesByNumbers().solution(9,6)); 23 | System.out.println(new ChocolatesByNumbers().solution(10,11)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/greedy/MaxNonOverlappingSegments.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.greedy; 2 | 3 | /** 4 | * This is the solution for Greedy algorithms > MaxNonoverlappingSegments 5 | * The problem is equivalent to the Activity Selection Problem, 6 | * where you have to choose the maximum non overlapping tasks. 7 | *

8 | * This is marked as PAINLESS difficulty 9 | */ 10 | 11 | public class MaxNonOverlappingSegments { 12 | public int solution(int[] A, int[] B) { 13 | int lastEndSegment = -1; 14 | int chosenCount = 0; 15 | for (int i = 0; i < A.length; i++) { 16 | if (A[i] > lastEndSegment) { 17 | chosenCount++; 18 | lastEndSegment = B[i]; 19 | } 20 | } 21 | return chosenCount; 22 | } 23 | 24 | public static void main(String[] args) { 25 | System.out.println(new MaxNonOverlappingSegments().solution(new int[]{1, 3, 7, 9, 9}, new int[]{5, 6, 8, 9, 10})); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/greedy/TieRopes.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.greedy; 2 | 3 | /** 4 | * This is the solution for Greedy > TieRope 5 | * 6 | * This is marked as PAINLESS difficulty 7 | */ 8 | public class TieRopes { 9 | public int solution(int K, int[] A) { 10 | int count = 0; 11 | int ropeLength = 0; 12 | for (int rope : A) { 13 | ropeLength += rope; 14 | if (ropeLength >= K) { 15 | count++; 16 | ropeLength = 0; 17 | } 18 | } 19 | return count; 20 | } 21 | 22 | public static void main(String[] args) { 23 | System.out.println(new TieRopes().solution(4, new int[]{1, 2, 3, 4, 1, 1, 3})); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/leader/Dominator.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.leader; 2 | 3 | /** 4 | * This is the solution for Leader > Dominator 5 | * 6 | * This is marked as PAINLESS difficulty 7 | */ 8 | 9 | public class Dominator { 10 | public int solution(int[] A) { 11 | int consecutiveSize = 0; 12 | int candidate = 0; 13 | for (int item : A) { 14 | if (consecutiveSize == 0) { 15 | candidate = item; 16 | consecutiveSize += 1; 17 | } else if (candidate == item) { 18 | consecutiveSize += 1; 19 | } else { 20 | consecutiveSize -= 1; 21 | } 22 | } 23 | 24 | int occurrence = 0; 25 | int index = 0; 26 | for (int i = 0; i < A.length; i++) { 27 | if (A[i] == candidate) { 28 | occurrence++; 29 | index = i; 30 | } 31 | } 32 | return occurrence > A.length / 2.0 ? index : -1; 33 | } 34 | 35 | public static void main(String[] args) { 36 | System.out.println(new Dominator().solution(new int[]{3, 0, 1, 1, 4, 1, 1})); 37 | System.out.println(new Dominator().solution(new int[]{1, 2, 3, 4, 5, 6, 7})); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/maximumsliceproblem/MaxProfit.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.maximumsliceproblem; 2 | 3 | /** 4 | * This is the solution for Maximum Slice Problem > Max Profit 5 | *

6 | * This is marked as PAINLESS difficulty 7 | */ 8 | 9 | public class MaxProfit { 10 | public int solution(int[] A) { 11 | int globalMaxSum = 0; 12 | int localMaxSum = 0; 13 | for (int i = 1; i < A.length; i++) { 14 | int d = A[i] - A[i - 1]; 15 | localMaxSum = Math.max(d, localMaxSum + d); 16 | globalMaxSum = Math.max(localMaxSum, globalMaxSum); 17 | } 18 | return globalMaxSum; 19 | } 20 | 21 | public static void main(String[] args) { 22 | // -2160, 112, 243, -353, 354 23 | System.out.println(new MaxProfit().solution(new int[]{23171, 21011, 21123, 21366, 21013, 21367})); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/prefixsums/CountDiv.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.prefixsums; 2 | 3 | /** 4 | * This is the solution for Prefix Sums > Count Div 5 | *

6 | * This is marked as Respectable difficulty 7 | */ 8 | 9 | 10 | public class CountDiv { 11 | public int solution(int A, int B, int K) { 12 | double nStart = Math.ceil(A / (double) K); 13 | double nEnd = Math.floor(B / (double) K); 14 | return (int) (nEnd - nStart + 1); 15 | } 16 | 17 | public static void main(String[] args) { 18 | System.out.println(new CountDiv().solution(6, 11, 2)); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/prefixsums/PassingCars.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.prefixsums; 2 | 3 | /** 4 | * This is the solution for Prefix Sums > Passing Cars 5 | *

6 | * This is marked as PAINLESS difficulty 7 | */ 8 | 9 | public class PassingCars { 10 | 11 | public int solution(int[] A) { 12 | int[] suffixSum = new int[A.length + 1]; 13 | int count = 0; 14 | for (int i = A.length - 1; i >= 0; i--) { 15 | suffixSum[i] = A[i] + suffixSum[i + 1]; 16 | if (A[i] == 0) count += suffixSum[i]; 17 | if (count > 1000000000) return -1; 18 | } 19 | 20 | return count; 21 | } 22 | 23 | public static void main(String[] args) { 24 | System.out.println(new PassingCars().solution(new int[]{0, 1, 0, 1, 1})); 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/prefixsums/countdivconsole.txt: -------------------------------------------------------------------------------- 1 | jshell> 6 / 2 2 | $1 ==> 3 3 | 4 | jshell> 7 / 2 5 | $2 ==> 3 6 | 7 | jshell> 7 / (double)2 8 | $5 ==> 3.5 9 | 10 | jshell> Math.ceil(7 / (double)2) 11 | $6 ==> 4.0 12 | 13 | jshell> Math.ceil(6 / (double)2) 14 | $7 ==> 3.0 15 | 16 | jshell> 11 / (double)2 17 | $8 ==> 5.5 18 | 19 | jshell> Math.floor(11/(double)2) 20 | $14 ==> 5.0 21 | 22 | jshell> Math.floor(10/(double)2) 23 | $15 ==> 5.0 24 | 25 | jshell> Math.floor(11/(double)2) - Math.ceil(6 / (double)2) + 1 26 | $13 ==> 3.0 -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/primeandcompositenumbers/Flags.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.primeandcompositenumbers; 2 | 3 | /** 4 | * This is the solution for Primes And Composite > Flags 5 | *

6 | * This is marked as Respectable difficulty 7 | */ 8 | 9 | public class Flags { 10 | public int solution(int[] A) { 11 | int nextPeak = A.length; 12 | int[] peaks = new int[A.length]; 13 | peaks[A.length - 1] = nextPeak; 14 | for (int i = A.length - 2; i > 0; i--) { 15 | if (A[i - 1] < A[i] && A[i + 1] < A[i]) 16 | nextPeak = i; 17 | peaks[i] = nextPeak; 18 | } 19 | peaks[0] = nextPeak; 20 | 21 | int current_guess = 0; 22 | int next_guess = 0; 23 | while (canPlaceFlags(peaks, next_guess)) { 24 | current_guess = next_guess; 25 | next_guess += 1; 26 | } 27 | 28 | return current_guess; 29 | } 30 | 31 | private boolean canPlaceFlags(int[] peaks, int flagsToPlace) { 32 | int currentPosition = 1 - flagsToPlace; 33 | for (int i = 0; i < flagsToPlace; i++) { 34 | if (currentPosition + flagsToPlace > peaks.length - 1) 35 | return false; 36 | currentPosition = peaks[currentPosition + flagsToPlace]; 37 | } 38 | return currentPosition < peaks.length; 39 | } 40 | 41 | public static void main(String[] args) { 42 | System.out.println(new Flags().solution(new int[]{1, 5, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2})); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/primeandcompositenumbers/FlagsFaster.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.primeandcompositenumbers; 2 | 3 | /** 4 | * This is the alternate solution for Primes And Composite > Flags 5 | *

6 | * This is marked as Respectable difficulty 7 | */ 8 | 9 | public class FlagsFaster { 10 | public int solution(int[] A) { 11 | int nextPeak = A.length; 12 | int[] peaks = new int[A.length]; 13 | peaks[A.length - 1] = nextPeak; 14 | for (int i = A.length - 2; i > 0; i--) { 15 | if (A[i - 1] < A[i] && A[i + 1] < A[i]) 16 | nextPeak = i; 17 | peaks[i] = nextPeak; 18 | } 19 | peaks[0] = nextPeak; 20 | 21 | int upper_guess = (int)Math.sqrt(A.length) + 2; 22 | int lower_guess = 0; 23 | while (lower_guess < upper_guess - 1) { 24 | int current_guess = (lower_guess + upper_guess) / 2; 25 | if (canPlaceFlags(peaks, current_guess)) 26 | lower_guess = current_guess; 27 | else 28 | upper_guess = current_guess; 29 | } 30 | 31 | return lower_guess; 32 | } 33 | 34 | private boolean canPlaceFlags(int[] peaks, int flagsToPlace) { 35 | int currentPosition = 1 - flagsToPlace; 36 | for (int i = 0; i < flagsToPlace; i++) { 37 | if (currentPosition + flagsToPlace > peaks.length - 1) 38 | return false; 39 | currentPosition = peaks[currentPosition + flagsToPlace]; 40 | } 41 | return currentPosition < peaks.length; 42 | } 43 | 44 | public static void main(String[] args) { 45 | System.out.println(new FlagsFaster().solution(new int[]{1, 5, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2})); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/sorting/NumberOfDiscIntersections.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.sorting; 2 | 3 | /** 4 | * This is the solution for Sorting > NumberOfDiscIntersections 5 | *

6 | * This is marked as RESPECTABLE difficulty 7 | */ 8 | 9 | import java.util.Arrays; 10 | 11 | public class NumberOfDiscIntersections { 12 | public int solution(int A[]) { 13 | int len = A.length; 14 | DiscLog[] discHistory = new DiscLog[len * 2]; 15 | int j = 0; 16 | for (int i = 0; i < len; i++) { 17 | discHistory[j++] = new DiscLog(i - (long) A[i], 1); 18 | discHistory[j++] = new DiscLog(i + (long) A[i], -1); 19 | } 20 | Arrays.sort(discHistory); 21 | int intersections = 0; 22 | int activeIntersections = 0; 23 | for (DiscLog log : discHistory) { 24 | activeIntersections += log.startEnd; 25 | if (log.startEnd > 0) intersections += activeIntersections - 1; 26 | if (intersections > 10000000) return -1; 27 | } 28 | return intersections; 29 | } 30 | 31 | class DiscLog implements Comparable { 32 | final long x; 33 | final int startEnd; 34 | 35 | DiscLog(long x, int startEnd) { 36 | this.x = x; 37 | this.startEnd = startEnd; 38 | } 39 | 40 | @Override 41 | public int compareTo(DiscLog b) { 42 | return this.x != b.x ? Long.compare(this.x, b.x) : Integer.compare(b.startEnd, this.startEnd); 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | System.out.println(new NumberOfDiscIntersections().solution(new int[]{1, 5, 2, 1, 4, 0})); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/sorting/NumberOfDiscIntersectionsAlt.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.sorting; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * This is the solution for Sorting > NumberOfDiscIntersections 7 | *

8 | * This is marked as RESPECTABLE difficulty 9 | */ 10 | 11 | public class NumberOfDiscIntersectionsAlt { 12 | 13 | private int indexLessThan(Disc[] sortedDiskList, double i, int start, int last) { 14 | int mid = start + (last - start) / 2; 15 | if (last <= start && sortedDiskList[mid].start > i) 16 | return mid - 1; 17 | if (last <= start) 18 | return mid; 19 | if (sortedDiskList[mid].start > i) 20 | return indexLessThan(sortedDiskList, i, start, mid - 1); 21 | else 22 | return indexLessThan(sortedDiskList, i, mid + 1, last); 23 | } 24 | 25 | public int solution(int A[]) { 26 | int len = A.length; 27 | Disc[] discs = new Disc[len]; 28 | for (int i = 0; i < len; i++) { 29 | discs[i] = new Disc(i - (long) A[i], i + (long) A[i]); 30 | } 31 | Arrays.sort(discs); 32 | int total = 0; 33 | for (int i = 0; i < len; i++) { 34 | total += indexLessThan(discs, discs[i].end + 0.5, 0, len - 1) - i; 35 | if (total > 10000000) return -1; 36 | } 37 | return total; 38 | } 39 | 40 | class Disc implements Comparable { 41 | final long start; 42 | final long end; 43 | 44 | Disc(long start, long end) { 45 | this.start = start; 46 | this.end = end; 47 | } 48 | 49 | @Override 50 | public int compareTo(Object o) { 51 | return Long.compare(start, ((Disc) o).start); 52 | } 53 | } 54 | 55 | public static void main(String[] args) { 56 | System.out.println(new NumberOfDiscIntersectionsAlt().solution(new int[]{1, 5, 2, 1, 4, 0})); 57 | } 58 | } -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/stacksandqueues/Brackets.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.stacksandqueues; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * This is the solution for Stacks And Queues > Brackets 7 | *

8 | * This is marked as PAINLESS difficulty 9 | */ 10 | public class Brackets { 11 | public int solution(String S) { 12 | Stack stack = new Stack<>(); 13 | for (char c : S.toCharArray()) { 14 | if (c == '{' || c == '[' || c == '(') { 15 | stack.push(c); 16 | } else if (c == '}') { 17 | if (stack.isEmpty() || stack.pop() != '{') return 0; 18 | } else if (c == ']') { 19 | if (stack.isEmpty() || stack.pop() != '[') return 0; 20 | } else if (c == ')') { 21 | if (stack.isEmpty() || stack.pop() != '(') return 0; 22 | } 23 | } 24 | return stack.isEmpty() ? 1 : 0; 25 | } 26 | 27 | public static void main(String[] args) { 28 | System.out.println(new Brackets().solution("()[]{}()[]{}")); 29 | System.out.println(new Brackets().solution("()]]")); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/stacksandqueues/Fish.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.stacksandqueues; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * This is the solution for Stacks And Queues > Fish 7 | *

8 | * This is marked as PAINLESS difficulty 9 | */ 10 | public class Fish { 11 | public int solution(int[] A, int[] B) { 12 | Stack stack = new Stack<>(); 13 | int survivors = 0; 14 | for (int i = 0; i < A.length; i++) { 15 | int weight = A[i]; 16 | if (B[i] == 1) { 17 | stack.push(weight); 18 | } else { 19 | int weightDown = stack.isEmpty() ? -1 : stack.pop(); 20 | while (weightDown != -1 && weightDown < weight) 21 | weightDown = stack.isEmpty() ? -1 : stack.pop(); 22 | if (weightDown == -1) 23 | survivors += 1; 24 | else 25 | stack.push(weightDown); 26 | } 27 | } 28 | return survivors + stack.size(); 29 | } 30 | 31 | public static void main(String[] args) { 32 | System.out.println(new Fish().solution(new int[]{4, 8, 2, 6, 7}, new int[]{0, 1, 1, 0, 0})); 33 | System.out.println(new Fish().solution(new int[]{4, 3, 2, 1, 5}, new int[]{0, 1, 0, 0, 0})); 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/timecomplexity/PermMissingElem.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.timecomplexity; 2 | 3 | /** 4 | * This is the solution for Time Complexity > PermMissingElem 5 | *

6 | * This is marked as PAINLESS difficulty 7 | */ 8 | public class PermMissingElem { 9 | public int solution(int[] A) { 10 | long actualSum = 0; 11 | for (int number: A) { 12 | actualSum += number; 13 | } 14 | long maxNumber = A.length + 1; 15 | long expectedSum = (maxNumber * (maxNumber + 1) / 2); 16 | return (int) (expectedSum - actualSum); 17 | } 18 | 19 | public static void main(String[] args) { 20 | System.out.println(new PermMissingElem().solution(new int[]{2, 3, 1, 5})); 21 | System.out.println(new PermMissingElem().solution(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9})); 22 | System.out.println(new PermMissingElem().solution(new int[]{})); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/cutajarjames/codility/timecomplexity/TapeEquilibrium.java: -------------------------------------------------------------------------------- 1 | package com.cutajarjames.codility.timecomplexity; 2 | 3 | /** 4 | * This is the solution for Time Complexity > TapeEquilibrium 5 | *

6 | * This is marked as PAINLESS difficulty 7 | */ 8 | public class TapeEquilibrium { 9 | public int solution(int[] A) { 10 | int leftSum = A[0]; 11 | int rightSum = 0; 12 | for (int x : A) 13 | rightSum += x; 14 | rightSum -= leftSum; 15 | 16 | int diff = Math.abs(leftSum - rightSum); 17 | for (int i = 1; i < A.length - 1; i++) { 18 | leftSum += A[i]; 19 | rightSum -= A[i]; 20 | int currentDiff = Math.abs(leftSum - rightSum); 21 | if (diff > currentDiff) diff = currentDiff; 22 | } 23 | return diff; 24 | } 25 | 26 | public static void main(String[] args) { 27 | System.out.println(new TapeEquilibrium().solution(new int[]{3, 1, 2, 4, 3})); 28 | } 29 | } --------------------------------------------------------------------------------