├── .gitignore ├── classic ├── search │ ├── pleb.js │ └── binarySearch.js ├── utils │ ├── isPrime.js │ ├── getFibonacciNum.js │ ├── reverseArray.js │ ├── numOfDivisors.js │ ├── isSemiPrime.js │ ├── getDivisors.js │ ├── getPrimes.js │ ├── greatestCommonDivisor.js │ ├── primeFactorization.js │ ├── getAllCombinations.js │ ├── getFibonacciSequence.js │ ├── leastCommonMultiple.js │ └── getSemiPrimes.js └── sorting │ ├── insertion.js │ ├── selection.js │ ├── bubble.js │ ├── shell.js │ ├── merge.js │ ├── quick.js │ └── tests.js ├── codility ├── futureTraining │ ├── strSymmetryPoint-string-reverse.js │ ├── arrayInversionCount.js │ └── treeHeight-binary-tree.js ├── 05_prefixSums │ ├── countDiv-divisible-in-range.js │ ├── passingCars.js │ ├── minAvgTwoSlice.js │ └── genomicRangeQuery.js ├── 10_primeAndCompositeNumbers │ ├── countFactors-count-divisors.js │ ├── minPerimeterRectangle-divisors.js │ ├── flags-peaks-higher-neighbors.js │ └── peaks-higher-neighbors.js ├── 06_sorting │ ├── distinct.js │ ├── maxProductOfThree-max-triplet-product.js │ ├── triangle-triplet-triangular.js │ └── numberOfDiscIntersections-radius.js ├── 02_arrays │ ├── cyclicRotation.js │ └── oddOccurrencesInArray.js ├── 04_countingElements │ ├── missingInteger-number-min-positive.js │ ├── permCheck-permutation.js │ ├── frogRiverOne-jump-earliest.js │ └── maxCounters.js ├── 03_timeComplexity │ ├── frogJmp-minimal-jumps.js │ ├── permMissingElem-number.js │ └── tapeEquilibrium-minimal-absolute-sum-difference.js ├── 07_stacksAndQueues │ ├── nesting-brackets-parens.js │ ├── brackets-nested-nesting.js │ ├── stoneWall-minimum-blocks-manhattan-skyline.js │ └── fish.js ├── 12_euclideanAlgorithm │ ├── chocolatesByNumbers-circle-greatest-common-divisor.js │ └── commonPrimeDivisors-prime-factorization.js ├── 09_maxSlice │ ├── maxSliceSum-max-subarray.js │ ├── maxProfit-max-subarray.js │ └── maxDoubleSliceSum.js ├── 15_caterpillarMethod │ ├── absDistinct-absolute-unique.js │ ├── countTriangles-triplet.js │ ├── countDistinctSlices-unique.js │ └── minAbsSumOfTwo-pairs.js ├── 01_iterations │ └── binaryGap-repeating-consecutive.js ├── 16_greedyAlgorithms │ ├── maxNonoverlappingSegments-common-point.js │ └── tieRopes-adjacent.js ├── 08_leader │ ├── dominator-leader-more-half.js │ └── equiLeader-more-half-same.js ├── 13_fibonacciNumbers │ ├── ladder-large-modulo-steps.js │ └── fibFrog-fibonacci-jump.js ├── 11_sieveOfEratosthenes │ ├── countNonDivisible.js │ └── countSemiPrimes.js ├── 17_dynamicProgramming │ └── numberSolitaire-dynamic-dice-six-marked.js ├── 14_binarySearchAlgorithm │ ├── minMaxDivision-divide-blocks-minimize-sum-binary-search.js │ └── nailingPlanks-minimal-number-used.js └── tests.js ├── notAlgorithms.js ├── beatmycode ├── aKingsTravel-chess.js ├── digitSum.js ├── missingNumber.js ├── chessboard-white-black.js ├── wordRank-combinations-lexicographic.js ├── decksOfCards-pairs.js ├── theTurtlePyramid-sort.js ├── circularPrimes-rotation.js └── minesweeper-matrix.js ├── package.json └── hackerrank ├── warmup ├── staircase.js ├── matrixDiagonalDiff.js ├── timeConversion.js └── plusMinus.js ├── implementation ├── chocolateFeast-wrappers-price.js ├── utopianTree.js ├── larrysArray-inversions-rotate-sort.js ├── cutTheSticks.js ├── manasaAndStones-trail-difference.js ├── sherlockAndTheBeast-3-5-decent.js ├── acmIcpcTeam-topics.js └── lisasWorkbook-page-chapters.js ├── strings ├── gameOfThrones1-palindrome-anagram.js └── palindromeIndex-string.js ├── search ├── pairs-difference.js └── iceCreamParlor.js ├── greedy ├── jimAndTheOrders-start-end.js └── largestPermutation-swap.js └── dynamicProgramming └── candies-neighbor-minimize.js /.gitignore: -------------------------------------------------------------------------------- 1 | classic/random 2 | codility/00_random 3 | hackerrank/00_random 4 | beatmycode/00_random 5 | current 6 | index.js 7 | 8 | .DS_Store 9 | 10 | node_modules -------------------------------------------------------------------------------- /classic/search/pleb.js: -------------------------------------------------------------------------------- 1 | function solution(A, el) { 2 | var len = A.length 3 | for (var i = 0; i < len; i++) if (A[i] === el) return i 4 | return -1 5 | } 6 | 7 | module.exports = solution 8 | -------------------------------------------------------------------------------- /classic/utils/isPrime.js: -------------------------------------------------------------------------------- 1 | function solution(N) { 2 | var i = 2 3 | 4 | while (i * i <= N) { 5 | if (N % i == 0) return false 6 | i += 1 7 | } 8 | 9 | return true 10 | } 11 | 12 | module.exports = solution 13 | -------------------------------------------------------------------------------- /classic/utils/getFibonacciNum.js: -------------------------------------------------------------------------------- 1 | function solution(N) { 2 | var x = Math.pow((1 + Math.sqrt(5)) / 2, N) 3 | var y = Math.pow(-2 / (1 + Math.sqrt(5)), N) 4 | return Math.round((x - y) / Math.sqrt(5)) 5 | } 6 | 7 | module.exports = solution 8 | -------------------------------------------------------------------------------- /classic/utils/reverseArray.js: -------------------------------------------------------------------------------- 1 | function solution(A) { 2 | var len = A.length-1 3 | 4 | for (var i = len; i > len/2; i--) { 5 | var temp = A[i] 6 | A[i] = A[len-i] 7 | A[len-i] = temp 8 | } 9 | 10 | return A 11 | } 12 | 13 | module.exports = solution 14 | -------------------------------------------------------------------------------- /classic/utils/numOfDivisors.js: -------------------------------------------------------------------------------- 1 | function solution(N) { 2 | var i = 1 3 | var count = 0 4 | 5 | while (i * i < N) { 6 | if (N % i == 0) count += 2 7 | i++ 8 | } 9 | 10 | if (i * i == N) count++ 11 | return count 12 | } 13 | 14 | module.exports = solution 15 | -------------------------------------------------------------------------------- /classic/utils/isSemiPrime.js: -------------------------------------------------------------------------------- 1 | function solution(N) { 2 | var a = 2 3 | var b = 0 4 | 5 | while (b < 3 && N != 1) { 6 | if (N % a === 0) { 7 | N = N / a 8 | b++ 9 | } else { 10 | a++ 11 | } 12 | } 13 | return b === 2 14 | } 15 | 16 | module.exports = solution 17 | -------------------------------------------------------------------------------- /classic/sorting/insertion.js: -------------------------------------------------------------------------------- 1 | function solution(A) { 2 | var len = A.length 3 | 4 | for (var i = 1; i < len; i++) { 5 | var el = A[i] 6 | 7 | for (var j = i-1; j >= 0 && el < A[j]; j--) { 8 | A[j+1] = A[j] 9 | } 10 | 11 | A[j+1] = el 12 | } 13 | 14 | return A 15 | } 16 | 17 | module.exports = solution 18 | -------------------------------------------------------------------------------- /codility/futureTraining/strSymmetryPoint-string-reverse.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(S) { 3 | var len = S.length 4 | if (!len || len%2 === 0) return -1 5 | 6 | var mid = (len-1)/2 7 | var left = S.slice(0, mid) 8 | var right = S.slice(mid+1) 9 | 10 | return left.split('').reverse().join('') === right ? mid : -1 11 | } 12 | 13 | module.exports = solution 14 | -------------------------------------------------------------------------------- /codility/futureTraining/arrayInversionCount.js: -------------------------------------------------------------------------------- 1 | // 72% 2 | function solution(A) { 3 | var len = A.length 4 | var count = 0 5 | 6 | for (var i = 0; i < len-1; i++) { 7 | for (var j = i+1; j < len; j++) { 8 | if (A[j] < A[i]) count++ 9 | } 10 | if (count > 1000000000) return -1 11 | } 12 | 13 | return count 14 | } 15 | 16 | module.exports = solution 17 | -------------------------------------------------------------------------------- /classic/utils/getDivisors.js: -------------------------------------------------------------------------------- 1 | function solution(N) { 2 | var divisors = [] 3 | var limit = Math.floor(Math.sqrt(N)) 4 | 5 | for (var i = 1; i <= limit; i++) { 6 | if (N % i === 0) { 7 | divisors.push(i) 8 | if (N / i !== i) divisors.push(N / i) 9 | } 10 | } 11 | 12 | divisors.sort((a, b) => a - b) 13 | return divisors 14 | } 15 | 16 | module.exports = solution 17 | -------------------------------------------------------------------------------- /classic/sorting/selection.js: -------------------------------------------------------------------------------- 1 | function solution(A) { 2 | var len = A.length 3 | 4 | for (var i = 0; i < len-1; i++) { 5 | var minIndex = i 6 | 7 | for (var j = i+1; j < len; j++) { 8 | if (A[minIndex] > A[j]) minIndex = j 9 | } 10 | 11 | var temp = A[minIndex] 12 | A[minIndex] = A[i] 13 | A[i] = temp 14 | } 15 | 16 | return A 17 | } 18 | 19 | module.exports = solution 20 | -------------------------------------------------------------------------------- /classic/utils/getPrimes.js: -------------------------------------------------------------------------------- 1 | function solution(N) { 2 | var i, p = 1 3 | var range = [] 4 | for (i = 0; i <= N; i++) range.push(true) 5 | 6 | while (p*p <= N) { 7 | if (!range[++p]) continue; 8 | for (i = p*p; i <= N; i += p) range[i] = false 9 | } 10 | 11 | var primes = [] 12 | for (i = 2; i <= N; i++) { 13 | if (range[i]) primes.push(i) 14 | } 15 | 16 | return primes 17 | } 18 | 19 | module.exports = solution 20 | -------------------------------------------------------------------------------- /classic/utils/greatestCommonDivisor.js: -------------------------------------------------------------------------------- 1 | function solution(A, B) { 2 | if (!B) return A 3 | return solution(B, A % B) 4 | } 5 | 6 | function solution(arr) { 7 | var len = arr.length 8 | var A = Math.abs(arr[0]) 9 | 10 | for (var i = 1; i < len; i++) { 11 | var B = Math.abs(arr[i]) 12 | 13 | while (A && B) { 14 | A > B ? A %= B : B %= A 15 | } 16 | A += B 17 | } 18 | return A 19 | } 20 | 21 | module.exports = solution 22 | -------------------------------------------------------------------------------- /classic/sorting/bubble.js: -------------------------------------------------------------------------------- 1 | function solution(A) { 2 | var end = A.length-1 3 | 4 | for (var i = 0; i < end; i++) { 5 | var modified = false 6 | 7 | for (var j = 0; j < end-i; j++) { 8 | if (A[j] > A[j+1]) { 9 | var temp = A[j+1] 10 | A[j+1] = A[j] 11 | A[j] = temp 12 | modified = true 13 | } 14 | } 15 | 16 | if (!modified) break; 17 | } 18 | 19 | return A 20 | } 21 | 22 | module.exports = solution 23 | -------------------------------------------------------------------------------- /classic/sorting/shell.js: -------------------------------------------------------------------------------- 1 | var solution = function(A) { 2 | var len = A.length 3 | var gap = Math.floor(len/2) 4 | 5 | while (gap > 0) { 6 | for (var i = gap; i < len; i++) { 7 | var el = A[i] 8 | 9 | for (var j = i-gap; j >= 0 && el < A[j]; j -= gap) { 10 | A[j+gap] = A[j] 11 | } 12 | 13 | A[j+gap] = el 14 | } 15 | 16 | gap = Math.floor(gap/2) 17 | } 18 | 19 | return A 20 | } 21 | 22 | module.exports = solution 23 | -------------------------------------------------------------------------------- /classic/utils/primeFactorization.js: -------------------------------------------------------------------------------- 1 | function primeFactors(N) { 2 | var primeFactors = {} 3 | var notDone = 1 < N 4 | 5 | while (notDone) { 6 | var P = 2 7 | var base = Math.sqrt(N) 8 | 9 | if (N % P) { 10 | P = 3 11 | while (N % P && P < base) P += 2 12 | } 13 | 14 | P = P > base ? N : P 15 | primeFactors[P] = P 16 | 17 | notDone = P !== N 18 | N = N / P 19 | } 20 | 21 | return primeFactors 22 | } 23 | 24 | module.exports = solution 25 | -------------------------------------------------------------------------------- /notAlgorithms.js: -------------------------------------------------------------------------------- 1 | // ugly curry-ish sum 2 | 3 | function sum() { 4 | var ret = arguments[0] 5 | 6 | for (var i = 1; i < arguments.length; i++) { 7 | ret += arguments[i] 8 | } 9 | 10 | return function next(x) { 11 | if (x === 'end') return ret 12 | 13 | var more = arguments[0] 14 | 15 | for (var j = 1; j < arguments.length; j++) { 16 | more += arguments[j] 17 | } 18 | 19 | ret += more 20 | return next 21 | } 22 | } 23 | 24 | console.log(sum(1, 2, 2)(5, 5, 5)(15, 20)('end')) -------------------------------------------------------------------------------- /classic/search/binarySearch.js: -------------------------------------------------------------------------------- 1 | function solution(A, el) { 2 | var len = A.length, 3 | start = 0, 4 | end = len-1, 5 | found 6 | 7 | while (typeof found === 'undefined' && end-start > -1) { 8 | 9 | var mid = Math.floor(start + (end-start)/2) 10 | if (el === A[mid]) found = mid 11 | 12 | if (el < A[mid]) { 13 | end = mid-1 14 | } else { 15 | start = mid+1 16 | } 17 | } 18 | 19 | return typeof found === 'undefined' ? -1 : found 20 | } 21 | 22 | module.exports = solution 23 | -------------------------------------------------------------------------------- /classic/utils/getAllCombinations.js: -------------------------------------------------------------------------------- 1 | function solution(arr) { 2 | var perm = [] 3 | var used = [] 4 | return permute(arr, perm, used) 5 | } 6 | 7 | function permute(arr, perm, used) { 8 | 9 | for (var i = 0; i < arr.length; i++) { 10 | var ch = arr.splice(i, 1)[0] 11 | used.push(ch) 12 | 13 | if (arr.length == 0) { 14 | perm.push(used.slice(0)) 15 | } 16 | 17 | permute(arr, perm, used) 18 | arr.splice(i, 0, ch) 19 | used.pop() 20 | } 21 | 22 | return perm 23 | } 24 | 25 | module.exports = solution 26 | -------------------------------------------------------------------------------- /beatmycode/aKingsTravel-chess.js: -------------------------------------------------------------------------------- 1 | function solution(N) { 2 | N = +N 3 | console.log(N === 1 ? 8 : Math.pow(N*2+1, 2)) 4 | } 5 | 6 | /*solution("BMC_TEST_INPUT_MAGIC")*/ 7 | 8 | module.exports = solution 9 | 10 | /*The king in chess can move to any neighboring square horizontally, vertically, or diagonally. Assuming that the king starts on some square of an infinite chessboard, in how many different squares can it be after N moves? 11 | 12 | N is at least 1. 13 | 14 | The "BMC_TEST_INPUT_MAGIC" (with quotes) in the code will be replaced with the actual value of the input. The input is in the format: "1234"*/ 15 | -------------------------------------------------------------------------------- /classic/utils/getFibonacciSequence.js: -------------------------------------------------------------------------------- 1 | // Up to Fib(N) 2 | function solution(N) { 3 | var last = 0, curr = 1 4 | var sequence = [0] 5 | 6 | while (N-- > 0) { 7 | var temp = last 8 | last = curr 9 | curr += temp 10 | sequence.push(last) 11 | } 12 | 13 | return sequence 14 | } 15 | 16 | // Up to N 17 | function solution(N) { 18 | var last = 0, curr = 1 19 | var sequence = [0] 20 | 21 | while (curr <= N) { 22 | var temp = last 23 | last = curr 24 | curr += temp 25 | sequence.push(last) 26 | } 27 | 28 | return sequence 29 | } 30 | 31 | module.exports = solution 32 | -------------------------------------------------------------------------------- /classic/utils/leastCommonMultiple.js: -------------------------------------------------------------------------------- 1 | function greatestCommonDivisor(A, B) { 2 | if (!B) return A 3 | return greatestCommonDivisor(B, A % B) 4 | } 5 | 6 | function solution(A, B) { 7 | return (A * B) / greatestCommonDivisor(A, B) 8 | } 9 | 10 | function solution(arr) { 11 | var len = arr.length 12 | var A = Math.abs(arr[0]) 13 | 14 | for (var i = 1; i < len; i++) { 15 | var B = Math.abs(arr[i]) 16 | var C = A 17 | 18 | while (A && B) { 19 | A > B ? A %= B : B %= A 20 | } 21 | A = Math.abs(C * arr[i]) / (A + B) 22 | } 23 | return A 24 | } 25 | 26 | module.exports = solution 27 | -------------------------------------------------------------------------------- /classic/utils/getSemiPrimes.js: -------------------------------------------------------------------------------- 1 | function solution(N) { 2 | var i = 0 3 | var primes = [] 4 | var semiPrimes = [] 5 | 6 | for (i = 2; i < N; i++) { 7 | primes[i] = true 8 | semiPrimes[i] = false 9 | } 10 | 11 | for (i = 2; i <= parseInt(Math.sqrt(N)); i++) { 12 | 13 | for (var j = i; j * i <= N; j++) { 14 | primes[j*i] = false 15 | 16 | if (primes[i] && primes[j]) { 17 | semiPrimes[j*i] = true 18 | } else { 19 | semiPrimes[j*i] = false 20 | } 21 | } 22 | } 23 | 24 | var result = [] 25 | for (i = 2; i <= N; i++) { 26 | if (semiPrimes[i]) result.push(i) 27 | } 28 | 29 | return result 30 | } 31 | 32 | module.exports = solution 33 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "algorithm_playground", 3 | "version": "1.0.0", 4 | "description": "Brushing up on CS", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/oldboyxx/algorithm_playground.git" 12 | }, 13 | "author": "", 14 | "license": "ISC", 15 | "bugs": { 16 | "url": "https://github.com/oldboyxx/algorithm_playground/issues" 17 | }, 18 | "homepage": "https://github.com/oldboyxx/algorithm_playground#readme", 19 | "dependencies": { 20 | "chai": "^3.5.0", 21 | "lodash": "^4.13.1", 22 | "performance-now": "^0.2.0" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /hackerrank/warmup/staircase.js: -------------------------------------------------------------------------------- 1 | function solution(N) { 2 | for (var i = 1; i <= N; i++) { 3 | console.log(' '.repeat(N-i) + '#'.repeat(i)) 4 | } 5 | } 6 | 7 | module.exports = solution 8 | 9 | /* 10 | Consider a staircase of size : 11 | 12 | # 13 | ## 14 | ### 15 | #### 16 | Observe that its base and height are both equal to , and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces. 17 | 18 | Write a program that prints a staircase of size . 19 | 20 | Input Format 21 | 22 | A single integer, , denoting the size of the staircase. 23 | 24 | Output Format 25 | 26 | Print a staircase of size using # symbols and spaces. 27 | 28 | Note: The last line must have spaces in it. 29 | */ -------------------------------------------------------------------------------- /beatmycode/digitSum.js: -------------------------------------------------------------------------------- 1 | function solution(input) { 2 | var N = +input 3 | var sum = 0 4 | 5 | for (var i = 1; i <= N; i++) { 6 | var num = i 7 | while (num) { 8 | sum += num % 10 9 | num = Math.floor(num/10) 10 | } 11 | } 12 | 13 | console.log(sum) 14 | } 15 | 16 | /*solution("BMC_TEST_INPUT_MAGIC")*/ 17 | 18 | module.exports = solution 19 | 20 | /* 21 | Find the sum of the digits of all the numbers from 1 to N (both ends included). 22 | 23 | For N = 10 the sum is 1+2+3+4+5+6+7+8+9+(1+0) = 46 24 | 25 | Preferably in O(logN) time. N is at least 1. 26 | 27 | The "BMC_TEST_INPUT_MAGIC" (with quotes) in the code will be replaced with the actual value of the input. The input is in the format: "1234" 28 | */ -------------------------------------------------------------------------------- /classic/sorting/merge.js: -------------------------------------------------------------------------------- 1 | function merge(left, right) { 2 | var l = 0, r = 0, 3 | result = [], 4 | leftLen = left.length, 5 | rightLen = right.length 6 | 7 | while (l < leftLen && r < rightLen) { 8 | if (left[l] < right[r]) { 9 | result.push(left[l++]) 10 | } else { 11 | result.push(right[r++]) 12 | } 13 | } 14 | 15 | while (l < leftLen) result.push(left[l++]) 16 | while (r < rightLen) result.push(right[r++]) 17 | 18 | return result 19 | } 20 | 21 | function solution(A) { 22 | var len = A.length 23 | if (len < 2) return A 24 | 25 | var mid = Math.ceil(len/2) 26 | var left = A.slice(0, mid) 27 | var right = A.slice(mid) 28 | 29 | return merge(solution(left), solution(right)) 30 | } 31 | 32 | module.exports = solution 33 | -------------------------------------------------------------------------------- /classic/sorting/quick.js: -------------------------------------------------------------------------------- 1 | function swap(A, x, y) { 2 | var temp = A[x] 3 | A[x] = A[y] 4 | A[y] = temp 5 | } 6 | 7 | function partition(A, wall, pivot) { 8 | var mid = wall + Math.round((pivot-wall)/2) 9 | swap(A, pivot, mid) 10 | 11 | for (var i = wall; i < pivot; i++) { 12 | if (A[i] < A[pivot]) { 13 | swap(A, i, wall) 14 | wall++ 15 | } 16 | } 17 | 18 | swap(A, pivot, wall) 19 | return wall 20 | } 21 | 22 | function divide(A, start, end) { 23 | var wall = partition(A, start, end) 24 | if (wall-start > 0) divide(A, start, wall-1) 25 | if (end-wall > 0) divide(A, wall+1, end) 26 | } 27 | 28 | function solution(A) { 29 | if (A.length < 2) return A 30 | divide(A, 0, A.length-1) 31 | return A 32 | } 33 | 34 | module.exports = solution 35 | -------------------------------------------------------------------------------- /hackerrank/warmup/matrixDiagonalDiff.js: -------------------------------------------------------------------------------- 1 | function solution(a) { 2 | var len = a.length-1 3 | var sum1 = 0 4 | var sum2 = 0 5 | 6 | for (var i = 0; i <= len; i++) { 7 | sum1 += a[i][i] 8 | sum2 += a[i][len-i] 9 | } 10 | 11 | var diff = Math.abs(sum1-sum2) 12 | 13 | console.log(diff) 14 | } 15 | 16 | module.exports = solution 17 | 18 | /* 19 | Given a square matrix of size , calculate the absolute difference between the sums of its diagonals. 20 | 21 | Input Format 22 | 23 | The first line contains a single integer, . The next lines denote the matrix's rows, with each line containing space-separated integers describing the columns. 24 | 25 | Output Format 26 | 27 | Print the absolute difference between the two sums of the matrix's diagonals as a single integer. 28 | */ -------------------------------------------------------------------------------- /beatmycode/missingNumber.js: -------------------------------------------------------------------------------- 1 | function solution(str) { 2 | var split = str.split(':') 3 | var N = split[0] 4 | var sequence = split[1].split(',') 5 | 6 | for (var i = 0; i < N; i++) { 7 | if (+sequence[i] !== i+1) { 8 | console.log(i+1) 9 | return 10 | } 11 | } 12 | } 13 | 14 | /*solution("BMC_TEST_INPUT_MAGIC")*/ 15 | 16 | module.exports = solution 17 | 18 | /* 19 | One number is deleted from the sequence 1,2,3, ... N. You get the numbers in a random order, and have to find the deleted one. Preferably in O(N). 20 | 21 | The "BMC_TEST_INPUT_MAGIC" (with quotes) in the code will be replaced with the actual value of the input. The input is in the format: "N:1,2,3,...,N" where N is the end of the sequence. Any item can be missing from 1 to N, so you get N-1 numbers! 22 | 23 | N is at least 1. 24 | 25 | Example: 26 | "8:1,2,3,4,5,6,8" -> 7 is the deleted item 27 | */ -------------------------------------------------------------------------------- /codility/05_prefixSums/countDiv-divisible-in-range.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A, B, K) { 3 | return Math.floor(B / K) - Math.floor((A - 1) / K) 4 | } 5 | 6 | module.exports = solution 7 | 8 | /* 9 | Write a function: 10 | 11 | int solution(int A, int B, int K); 12 | 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.: 13 | 14 | { i : A ≤ i ≤ B, i mod K = 0 } 15 | 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. 16 | 17 | Assume that: 18 | 19 | A and B are integers within the range [0..2,000,000,000]; 20 | K is an integer within the range [1..2,000,000,000]; 21 | A ≤ B. 22 | Complexity: 23 | 24 | expected worst-case time complexity is O(1); 25 | expected worst-case space complexity is O(1). 26 | */ -------------------------------------------------------------------------------- /hackerrank/implementation/chocolateFeast-wrappers-price.js: -------------------------------------------------------------------------------- 1 | function solution(N, C, M) { 2 | var forCash = Math.floor(N / C) 3 | var count = forCash 4 | var wrappers = forCash 5 | 6 | while (wrappers >= M) { 7 | var extra = Math.floor(wrappers / M) 8 | count += extra 9 | wrappers -= extra*(M-1) 10 | } 11 | 12 | console.log(count) 13 | } 14 | 15 | module.exports = solution 16 | 17 | /* 18 | Little Bob loves chocolate, and he goes to a store with in his pocket. The price of each chocolate is . The store offers a discount: for every wrappers he gives to the store, he gets one chocolate for free. How many chocolates does Bob get to eat? 19 | 20 | Input Format: 21 | The first line contains the number of test cases, . 22 | lines follow, each of which contains three integers, , , and . 23 | 24 | Output Format: 25 | Print the total number of chocolates Bob eats. 26 | */ -------------------------------------------------------------------------------- /hackerrank/implementation/utopianTree.js: -------------------------------------------------------------------------------- 1 | function solution(N) { 2 | var height = 1 3 | for (var i = 1; i <= N; i++) { 4 | i % 2 ? height *= 2 : height++ 5 | } 6 | console.log(height) 7 | } 8 | 9 | module.exports = solution 10 | 11 | /* 12 | The Utopian Tree goes through 2 cycles of growth every year. Each spring, it doubles in height. Each summer, its height increases by 1 meter. 13 | 14 | Laura plants a Utopian Tree sapling with a height of 1 meter at the onset of spring. How tall will her tree be after growth cycles? 15 | 16 | Input Format 17 | 18 | The first line contains an integer, , the number of test cases. 19 | subsequent lines each contain an integer, , denoting the number of cycles for that test case. 20 | 21 | Constraints 22 | 23 | 24 | Output Format 25 | 26 | For each test case, print the height of the Utopian Tree after cycles. Each height must be printed on a new line. 27 | */ -------------------------------------------------------------------------------- /hackerrank/warmup/timeConversion.js: -------------------------------------------------------------------------------- 1 | function solution(time) { 2 | 3 | if (/PM/.test(time)) { 4 | time = time.replace('PM', '') 5 | var hours = time.slice(0, 2) 6 | if (hours !== '12') hours = (parseInt(hours) + 12).toString() 7 | console.log(hours+time.slice(2)) 8 | 9 | } else { 10 | time = time.replace('AM', '') 11 | var hours = time.slice(0, 2) 12 | if (hours === '12') hours = '00' 13 | console.log(hours+time.slice(2)) 14 | } 15 | } 16 | 17 | module.exports = solution 18 | 19 | /* 20 | Given a time in AM/PM format, convert it to military (-hour) time. 21 | 22 | Note: Midnight is on a -hour clock, and on a -hour clock. Noon is on a -hour clock, and on a -hour clock. 23 | 24 | Input Format 25 | 26 | A single string containing a time in -hour clock format (i.e.: or ), where . 27 | 28 | Output Format 29 | 30 | Convert and print the given time in -hour format, where . 31 | 32 | Sample Input 33 | 34 | 07:05:45PM 35 | Sample Output 36 | 37 | 19:05:45 38 | */ -------------------------------------------------------------------------------- /beatmycode/chessboard-white-black.js: -------------------------------------------------------------------------------- 1 | function solution(str) { 2 | var N = +str.split(',')[0] 3 | var M = +str.split(',')[1] 4 | 5 | for (var i = 2; i < M+2; i++) { 6 | var str = '' 7 | if (i % 2 === 0) { 8 | for (var j = 2; j < N+2; j++) str += j % 2 === 0 ? 0 : 1 9 | } else { 10 | for (var j = 1; j < N+1; j++) str += j % 2 === 0 ? 0 : 1 11 | } 12 | console.log(str) 13 | } 14 | } 15 | 16 | /*solution("BMC_TEST_INPUT_MAGIC")*/ 17 | 18 | module.exports = solution 19 | 20 | /* 21 | Print to the standard output a chessboard of size N,M where N is the number of columns and M is the number of rows. 22 | You have to print a 0 where the board is white and a 1 otherwise. 23 | Index (0,0) is white and it is the top left cell in the produced output. 24 | 25 | The "BMC_TEST_INPUT_MAGIC" (with quotes) in the code will be replaced with the actual value of the input. It's a string in the form of "N,M". 26 | 27 | Sample input: 28 | 7,4 29 | 30 | Sample output: 31 | 0101010 32 | 1010101 33 | 0101010 34 | 1010101 35 | */ 36 | -------------------------------------------------------------------------------- /codility/10_primeAndCompositeNumbers/countFactors-count-divisors.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(N) { 3 | var i = 1 4 | var count = 0 5 | 6 | while (i * i < N) { 7 | if (N % i === 0) count += 2 8 | i++ 9 | } 10 | 11 | if (i * i == N) count++ 12 | return count 13 | } 14 | 15 | module.exports = solution 16 | 17 | /* 18 | A positive integer D is a factor of a positive integer N if there exists an integer M such that N = D * M. 19 | 20 | For example, 6 is a factor of 24, because M = 4 satisfies the above condition (24 = 6 * 4). 21 | 22 | Write a function: 23 | 24 | int solution(int N); 25 | that, given a positive integer N, returns the number of its factors. 26 | 27 | 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. 28 | 29 | Assume that: 30 | 31 | N is an integer within the range [1..2,147,483,647]. 32 | Complexity: 33 | 34 | expected worst-case time complexity is O(sqrt(N)); 35 | expected worst-case space complexity is O(1). 36 | */ -------------------------------------------------------------------------------- /hackerrank/strings/gameOfThrones1-palindrome-anagram.js: -------------------------------------------------------------------------------- 1 | function solution(S) { 2 | var chars = {} 3 | for (var i = 0; i < S.length; i++) { 4 | chars[S[i]] = chars[S[i]] ? chars[S[i]]+1 : 1 5 | } 6 | 7 | var nonEvenCount = 0 8 | for (c in chars) { 9 | if (chars[c] % 2) nonEvenCount++ 10 | } 11 | 12 | console.log(nonEvenCount > 1 ? 'NO' : 'YES') 13 | } 14 | 15 | module.exports = solution 16 | 17 | /* 18 | Dothraki are planning an attack to usurp King Robert's throne. King Robert learns of this conspiracy from Raven and plans to lock the single door through which the enemy can enter his kingdom. 19 | 20 | But, to lock the door he needs a key that is an anagram of a certain palindrome string. 21 | 22 | The king has a string composed of lowercase English letters. Help him figure out whether any anagram of the string can be a palindrome or not. 23 | 24 | Input Format 25 | A single line which contains the input string. 26 | 27 | Constraints 28 | length of string 29 | Each character of the string is a lowercase English letter. 30 | 31 | Output Format 32 | A single line which contains YES or NO in uppercase. 33 | */ -------------------------------------------------------------------------------- /hackerrank/search/pairs-difference.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(input) { 3 | input = input.split('\n') 4 | var K = +input[0].split(' ')[1] 5 | var A = input[1].split(' ') 6 | var len = A.length, i, j 7 | for (i = 0; i < len; i++) A[i] = +A[i] 8 | 9 | var vals = {} 10 | for (i = 0; i < len; i++) { 11 | vals[A[i]] = vals[A[i]] || [] 12 | vals[A[i]].push(i) 13 | } 14 | 15 | var pairs = 0 16 | for (i = 0; i < len; i++) { 17 | var t1 = vals[A[i]+K], t2 = vals[A[i]-K] 18 | if (t1) { 19 | for (j = 0; j < t1.length; j++) { 20 | if (t1[j] > i) pairs++ 21 | } 22 | } 23 | if (t2) { 24 | for (j = 0; j < t2.length; j++) { 25 | if (t2[j] > i) pairs++ 26 | } 27 | } 28 | } 29 | 30 | console.log(pairs) 31 | } 32 | 33 | module.exports = solution 34 | 35 | /* 36 | Given integers, count the number of pairs of integers whose difference is . 37 | 38 | Input Format 39 | 40 | The first line contains and . 41 | The second line contains numbers of the set. All the numbers are unique. 42 | 43 | Output Format 44 | 45 | An integer that tells the number of pairs of integers whose difference is . 46 | */ -------------------------------------------------------------------------------- /codility/futureTraining/treeHeight-binary-tree.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | var path 3 | 4 | function currIsEmpty() { 5 | var n = path[path.length-1] 6 | return n.l === null && n.r === null 7 | } 8 | 9 | function node() { 10 | return path[path.length-1] 11 | } 12 | 13 | function solution(T) { 14 | var maxLevel = 1 15 | var lastDirection 16 | path = [] 17 | path.push(T) 18 | 19 | while (T.l !== null || T.r !== null) { 20 | 21 | if (currIsEmpty()) { 22 | path.pop() 23 | node()[lastDirection] = null 24 | } 25 | 26 | if (node().l) { 27 | lastDirection = 'l' 28 | path.push(node().l) 29 | maxLevel = Math.max(maxLevel, path.length) 30 | 31 | } else if (node().r) { 32 | lastDirection = 'r' 33 | path.push(node().r) 34 | maxLevel = Math.max(maxLevel, path.length) 35 | } 36 | } 37 | 38 | return maxLevel-1 39 | } 40 | 41 | // 100% 42 | function solution(T) { 43 | return travel(T) 44 | } 45 | 46 | function travel(node) { 47 | if (!node) return -1 48 | var heightLeft = travel(node.l) 49 | var heightRight = travel(node.r) 50 | return 1 + Math.max(heightLeft, heightRight) 51 | } 52 | 53 | module.exports = solution 54 | -------------------------------------------------------------------------------- /codility/06_sorting/distinct.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | var uniq = {} 5 | var size = 0 6 | 7 | for (var i = 0; i < len; i++) { 8 | if (!uniq[A[i]]) { 9 | uniq[A[i]] = true 10 | size++ 11 | } 12 | } 13 | 14 | return size 15 | } 16 | 17 | module.exports = solution 18 | 19 | /* 20 | Write a function 21 | 22 | int solution(int A[], int N); 23 | that, given a zero-indexed array A consisting of N integers, returns the number of distinct values in array A. 24 | 25 | Assume that: 26 | 27 | N is an integer within the range [0..100,000]; 28 | each element of array A is an integer within the range [−1,000,000..1,000,000]. 29 | For example, given array A consisting of six elements such that: 30 | 31 | A[0] = 2 A[1] = 1 A[2] = 1 32 | A[3] = 2 A[4] = 3 A[5] = 1 33 | the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3. 34 | 35 | Complexity: 36 | 37 | expected worst-case time complexity is O(N*log(N)); 38 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 39 | Elements of input arrays can be modified. 40 | */ -------------------------------------------------------------------------------- /codility/02_arrays/cyclicRotation.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A, K) { 3 | if (!A.length || A.length === 1) return A 4 | while (K--) A.unshift(A.pop()) 5 | return A 6 | } 7 | 8 | module.exports = solution 9 | 10 | /* 11 | A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place. 12 | 13 | For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times; that is, each element of A will be shifted to the right by K indexes. 14 | 15 | Write a function: 16 | 17 | struct Results solution(int A[], int N, int K); 18 | that, given a zero-indexed array A consisting of N integers and an integer K, returns the array A rotated K times. 19 | 20 | For example, given array A = [3, 8, 9, 7, 6] and K = 3, the function should return [9, 7, 6, 3, 8]. 21 | 22 | Assume that: 23 | 24 | N and K are integers within the range [0..100]; 25 | each element of array A is an integer within the range [−1,000..1,000]. 26 | In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment. 27 | */ -------------------------------------------------------------------------------- /codility/04_countingElements/missingInteger-number-min-positive.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | A = A.filter(n => n > 0) 4 | A.sort((a, b) => a - b) 5 | 6 | var next = 0 7 | var len = A.length 8 | if (!len) return 1 9 | 10 | for (var i = 0; i < len; i++) { 11 | if (next !== A[i]) next++ 12 | if (next !== A[i]) return next 13 | } 14 | 15 | return A[len-1] + 1 16 | } 17 | 18 | module.exports = solution 19 | 20 | /* 21 | Write a function: 22 | 23 | int solution(int A[], int N); 24 | that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer (greater than 0) that does not occur in A. 25 | 26 | For example, given: 27 | 28 | A[0] = 1 29 | A[1] = 3 30 | A[2] = 6 31 | A[3] = 4 32 | A[4] = 1 33 | A[5] = 2 34 | the function should return 5. 35 | 36 | Assume that: 37 | 38 | N is an integer within the range [1..100,000]; 39 | each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]. 40 | Complexity: 41 | 42 | expected worst-case time complexity is O(N); 43 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 44 | Elements of input arrays can be modified. 45 | */ -------------------------------------------------------------------------------- /codility/03_timeComplexity/frogJmp-minimal-jumps.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(X, Y, D) { 3 | return Math.ceil((Y - X) / D) 4 | } 5 | 6 | module.exports = solution 7 | 8 | /* 9 | 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. 10 | 11 | Count the minimal number of jumps that the small frog must perform to reach its target. 12 | 13 | Write a function: 14 | 15 | int solution(int X, int Y, int D); 16 | 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. 17 | 18 | For example, given: 19 | 20 | X = 10 21 | Y = 85 22 | D = 30 23 | the function should return 3, because the frog will be positioned as follows: 24 | 25 | after the first jump, at position 10 + 30 = 40 26 | after the second jump, at position 10 + 30 + 30 = 70 27 | after the third jump, at position 10 + 30 + 30 + 30 = 100 28 | Assume that: 29 | 30 | X, Y and D are integers within the range [1..1,000,000,000]; 31 | X ≤ Y. 32 | Complexity: 33 | 34 | expected worst-case time complexity is O(1); 35 | expected worst-case space complexity is O(1). 36 | */ -------------------------------------------------------------------------------- /hackerrank/greedy/jimAndTheOrders-start-end.js: -------------------------------------------------------------------------------- 1 | function solution(input) { 2 | input = input.split('\n').slice(1) 3 | var A = [], i 4 | for (i = 0; i < input.length; i++) { 5 | A.push([+input[i].split(' ')[0], +input[i].split(' ')[1]]) 6 | } 7 | 8 | var sums = [] 9 | for (i = 0; i < A.length; i++) { 10 | sums.push({ index: i, sum: A[i][0] + A[i][1] }) 11 | } 12 | 13 | sums.sort((a, b) => a.sum - b.sum) 14 | 15 | var ret = sums[0].index+1 16 | for (i = 1; i < sums.length; i++) { 17 | var x = sums[i].index+1 18 | ret += (' '+x) 19 | } 20 | console.log(ret) 21 | } 22 | 23 | module.exports = solution 24 | 25 | /* 26 | In Jim's Burger, hungry burger fans are ordering burgers. The th order is placed by the th fan at time and it takes time to process. What is the order in which the fans will get their burgers? 27 | 28 | Input Format 29 | On the first line you will get , the number of orders. Then lines will follow. On the th line, you will get and separated by a single space. 30 | 31 | Output Format 32 | Print the order ( as single space separated integers ) in which the burger fans get their burgers. If two fans get the burger at the same time, then print the smallest numbered order first.(remember, the fans are numbered 1 to ). 33 | */ -------------------------------------------------------------------------------- /beatmycode/wordRank-combinations-lexicographic.js: -------------------------------------------------------------------------------- 1 | function solution(str) { 2 | var perm = [] 3 | var used = [] 4 | var arr = permute(str.split(''), perm, used) 5 | 6 | for (var i = 0; i < arr.length; i++) arr[i] = arr[i].join('') 7 | arr.sort() 8 | console.log(arr.indexOf(str)+1) 9 | } 10 | 11 | function permute(arr, perm, used) { 12 | 13 | for (var i = 0; i < arr.length; i++) { 14 | var ch = arr.splice(i, 1)[0] 15 | used.push(ch) 16 | 17 | if (arr.length == 0) { 18 | perm.push(used.slice(0)) 19 | } 20 | 21 | permute(arr, perm, used) 22 | arr.splice(i, 0, ch) 23 | used.pop() 24 | } 25 | 26 | return perm 27 | } 28 | 29 | /*solution("BMC_TEST_INPUT_MAGIC")*/ 30 | 31 | module.exports = solution 32 | 33 | /* 34 | You are given a word as input: "WORD" 35 | 36 | If we generate a list of all “words” (including duplicates) made up of the letters in "WORD" (in this case W, O, R and D), in lexicographic order starting with DORW and ending with WROD, what position in the list will be occupied by the word "WORD"? If the word occurs more than once, the first position should be returned. 37 | 38 | The "BMC_TEST_INPUT_MAGIC" (with quotes) in the code will be replaced with the actual value of the input. 39 | 40 | Example input: TURING 41 | Example output: 598 42 | */ -------------------------------------------------------------------------------- /hackerrank/greedy/largestPermutation-swap.js: -------------------------------------------------------------------------------- 1 | function solution(input) { 2 | input = input.split('\n') 3 | var K = +input[0].split(' ')[1] 4 | var A = input[1].split(' ') 5 | var i 6 | for (i = 0; i < A.length; i++) A[i] = +A[i] 7 | 8 | var indexes = {} 9 | for (i = 0; i < A.length; i++) indexes[A[i]] = i 10 | 11 | for (i = 0; i < A.length; i++) { 12 | var N = A.length-i 13 | 14 | if (A[i] !== N) { 15 | var _Ai = A[i], _AN = A[indexes[N]], _iN = indexes[N] 16 | A[i] = _AN 17 | A[_iN] = _Ai 18 | indexes[_Ai] = _iN 19 | indexes[N] = i 20 | if (!--K) break; 21 | } 22 | } 23 | 24 | console.log(A.join(' ')) 25 | } 26 | 27 | module.exports = solution 28 | 29 | /* 30 | You are given an array of integers which is a permutation of the first natural numbers. You can swap any two elements of the array. You can make at most swaps. What is the largest permutation, in numerical order, you can make? 31 | 32 | Input Format 33 | The first line of the input contains two integers, and , the size of the input array and the maximum swaps you can make, respectively. The second line of the input contains a permutation of the first natural numbers. 34 | 35 | Output Format 36 | Print the lexicographically largest permutation you can make with at most swaps. 37 | */ -------------------------------------------------------------------------------- /classic/sorting/tests.js: -------------------------------------------------------------------------------- 1 | describe('Algorithm', () => { 2 | 3 | it('is accurate', (done) => { 4 | var A = [] 5 | for (var i = 0; i < 1000; i++) { 6 | A.push(i-_.random(495, 500)) 7 | } 8 | 9 | expect(solution([])).to.deep.equal([]) 10 | expect(solution([1])).to.deep.equal([1]) 11 | expect(solution([0])).to.deep.equal([0]) 12 | expect(solution([1, 0, 1, 0, 1, 0])).to.deep.equal([0, 0, 0, 1, 1, 1]) 13 | expect(solution([1, 1, 1])).to.deep.equal([1, 1, 1]) 14 | expect(solution([0, 1, 1])).to.deep.equal([0, 1, 1]) 15 | expect(solution([-5, 14, 1, -50, 55, 0, 1, -5, -4, -1])) 16 | .to.deep.equal([-5, 14, 1, -50, 55, 0, 1, -5, -4, -1].sort((a,b) => a-b)) 17 | expect(solution([-50, 1, -5, 14, 1, -50, 55, 0, -4, -1, 1, 1])) 18 | .to.deep.equal([-50, 1, -5, 14, 1, -50, 55, 0, -4, -1, 1, 1].sort((a,b) => a-b)) 19 | expect(solution(_.shuffle(A))).to.deep.equal(A.sort((a,b) => a-b)) 20 | expect(solution(A)).to.deep.equal(A.sort((a,b) => a-b)) 21 | expect(solution(_.reverse(A.sort((a,b) => a-b)))).to.deep.equal(A.sort((a,b) => a-b)) 22 | done() 23 | }) 24 | 25 | it('is fast', (done) => { 26 | var A = [] 27 | for (var i = 0; i < 1000000; i++) { 28 | A.push(i-500000) 29 | } 30 | 31 | run([_.shuffle(A)], 1) 32 | 33 | done() 34 | }) 35 | }) -------------------------------------------------------------------------------- /codility/03_timeComplexity/permMissingElem-number.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | A.sort((a, b) => a - b) 4 | var len = A.length 5 | 6 | for (var i = 0; i <= len; i++) { 7 | if (i+1 !== A[i]) { 8 | missing = i+1 9 | break; 10 | } 11 | } 12 | 13 | return missing 14 | } 15 | 16 | module.exports = solution 17 | 18 | /* 19 | 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. 20 | 21 | Your goal is to find that missing element. 22 | 23 | Write a function: 24 | 25 | int solution(int A[], int N); 26 | that, given a zero-indexed array A, returns the value of the missing element. 27 | 28 | For example, given array A such that: 29 | 30 | A[0] = 2 31 | A[1] = 3 32 | A[2] = 1 33 | A[3] = 5 34 | the function should return 4, as it is the missing element. 35 | 36 | Assume that: 37 | 38 | N is an integer within the range [0..100,000]; 39 | the elements of A are all distinct; 40 | each element of array A is an integer within the range [1..(N + 1)]. 41 | Complexity: 42 | 43 | expected worst-case time complexity is O(N); 44 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments). 45 | Elements of input arrays can be modified. 46 | */ -------------------------------------------------------------------------------- /beatmycode/decksOfCards-pairs.js: -------------------------------------------------------------------------------- 1 | function solution(str) { 2 | var A = str.split(',') 3 | if (!A.length) { console.log(0); return; } 4 | var i, uniqCounts = {} 5 | 6 | for (i = 0; i < A.length; i++) uniqCounts[A[i]] = 0 7 | for (i = 0; i < A.length; i++) uniqCounts[A[i]]++ 8 | 9 | var counts = [] 10 | for (k in uniqCounts) counts.push(uniqCounts[k]) 11 | 12 | if (counts.length !== 52) { console.log(0); return; } 13 | max = Math.min.apply(null, counts) 14 | 15 | console.log(max) 16 | } 17 | 18 | /*solution("BMC_TEST_INPUT_MAGIC")*/ 19 | 20 | module.exports = solution 21 | 22 | /* 23 | In a casino all the playing cards got mixed up, and a lot of them got lost. You have to collect as many full decks as possible. A deck contains 52 cards, one for each rank and suit. 24 | 25 | You get N mixed up French playing cards as your input. 26 | 27 | You have to output the number of full decks. 28 | 29 | The cards are of the following ranks: 30 | 2,3,4,5,6,7,8,9,T,J,Q,K,A 31 | 32 | The four suits are: 33 | Spade(♠), Club(♣), Heart(♥), and Diamond(♦) 34 | 35 | The cards are given using their rank followed by their suit: 36 | 37 | 2 of Spades: 2S 38 | Ace of Clubs: AC 39 | 10 of Hearts: TH 40 | 41 | The "BMC_TEST_INPUT_MAGIC" (with quotes) in the code will be replaced with the actual value of the input. The input is in the format: "2S,AC,TH". 42 | */ -------------------------------------------------------------------------------- /hackerrank/implementation/larrysArray-inversions-rotate-sort.js: -------------------------------------------------------------------------------- 1 | function solution(input) { 2 | input = input.split('\n') 3 | 4 | for (var k = 1; k < input.length; k += 2) { 5 | var A = input[k+1].split(' ') 6 | var len = A.length 7 | var inversions = 0 8 | 9 | for (var i = 0; i < len-1; i++) { 10 | for (var j = i+1; j < len; j++) { 11 | if (+A[i] > +A[j]) inversions++ 12 | } 13 | } 14 | 15 | console.log(inversions % 2 === 0 ? 'YES' : 'NO') 16 | } 17 | } 18 | 19 | module.exports = solution 20 | 21 | /* 22 | Larry has a permutation of numbers, , whose unique elements range from to (i.e.: ). He wants to be sorted, so he delegates the task of doing so to his robot. The robot can perform the following operation as many times as it wants: 23 | 24 | Choose any consecutive indices and rotate their elements in such a way that rotates to , which rotates to , which rotates back to . 25 | For example: if and the robot rotates , becomes . 26 | 27 | On a new line for each test case, print if the robot can fully sort ; otherwise, print . 28 | 29 | Input Format 30 | 31 | The first line contains an integer, , the number of test cases. 32 | The subsequent lines each describe a test case over lines: 33 | 34 | An integer, , denoting the size of . 35 | space-separated integers describing , where the value describes element . 36 | */ -------------------------------------------------------------------------------- /codility/07_stacksAndQueues/nesting-brackets-parens.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(S) { 3 | var len = S.length 4 | var open = 0 5 | var closed = 0 6 | 7 | for (var i = 0; i < len; i++) { 8 | if (S[i] === '(') { 9 | open++ 10 | } else { 11 | closed++ 12 | } 13 | 14 | if (open < closed) return 0 15 | } 16 | 17 | return open === closed ? 1 : 0 18 | } 19 | 20 | module.exports = solution 21 | 22 | /* 23 | A string S consisting of N characters is called properly nested if: 24 | 25 | S is empty; 26 | S has the form "(U)" where U is a properly nested string; 27 | S has the form "VW" where V and W are properly nested strings. 28 | For example, string "(()(())())" is properly nested but string "())" isn't. 29 | 30 | Write a function: 31 | 32 | int solution(char *S); 33 | that, given a string S consisting of N characters, returns 1 if string S is properly nested and 0 otherwise. 34 | 35 | For example, given S = "(()(())())", the function should return 1 and given S = "())", the function should return 0, as explained above. 36 | 37 | Assume that: 38 | 39 | N is an integer within the range [0..1,000,000]; 40 | string S consists only of the characters "(" and/or ")". 41 | Complexity: 42 | 43 | expected worst-case time complexity is O(N); 44 | expected worst-case space complexity is O(1) (not counting the storage required for input arguments). 45 | */ -------------------------------------------------------------------------------- /hackerrank/warmup/plusMinus.js: -------------------------------------------------------------------------------- 1 | function solution(A) { 2 | var len = A.length 3 | var pos = 0, neg = 0, zero = 0 4 | 5 | for (var i = 0; i < len; i++) { 6 | if (A[i] > 0) { 7 | pos++ 8 | } else if (A[i] < 0) { 9 | neg++ 10 | } else { 11 | zero++ 12 | } 13 | } 14 | 15 | console.log((pos/len).toFixed(6)) 16 | console.log((neg/len).toFixed(6)) 17 | console.log((zero/len).toFixed(6)) 18 | } 19 | 20 | module.exports = solution 21 | 22 | /* 23 | Given an array of integers, calculate which fraction of its elements are positive, which fraction of its elements are negative, and which fraction of its elements are zeroes, respectively. Print the decimal value of each fraction on a new line. 24 | 25 | Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to are acceptable. 26 | 27 | Input Format 28 | 29 | The first line contains an integer, , denoting the size of the array. 30 | The second line contains space-separated integers describing an array of numbers . 31 | 32 | Output Format 33 | 34 | You must print the following lines: 35 | 36 | A decimal representing of the fraction of positive numbers in the array. 37 | A decimal representing of the fraction of negative numbers in the array. 38 | A decimal representing of the fraction of zeroes in the array. 39 | */ -------------------------------------------------------------------------------- /codility/10_primeAndCompositeNumbers/minPerimeterRectangle-divisors.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(N) { 3 | var A = 1 4 | var minPerim = Infinity 5 | 6 | while (A * A <= N) { 7 | if (N % A === 0) { 8 | var B = N / A 9 | minPerim = Math.min(minPerim, 2*(A+B)) 10 | } 11 | 12 | A++ 13 | } 14 | 15 | return minPerim 16 | } 17 | 18 | module.exports = solution 19 | 20 | /* 21 | An integer N is given, representing the area of some rectangle. 22 | 23 | The area of a rectangle whose sides are of length A and B is A * B, and the perimeter is 2 * (A + B). 24 | 25 | The goal is to find the minimal perimeter of any rectangle whose area equals N. The sides of this rectangle should be only integers. 26 | 27 | For example, given integer N = 30, rectangles of area 30 are: 28 | 29 | (1, 30), with a perimeter of 62, 30 | (2, 15), with a perimeter of 34, 31 | (3, 10), with a perimeter of 26, 32 | (5, 6), with a perimeter of 22. 33 | Write a function: 34 | 35 | int solution(int N); 36 | that, given an integer N, returns the minimal perimeter of any rectangle whose area is exactly equal to N. 37 | 38 | For example, given an integer N = 30, the function should return 22, as explained above. 39 | 40 | Assume that: 41 | 42 | N is an integer within the range [1..1,000,000,000]. 43 | Complexity: 44 | 45 | expected worst-case time complexity is O(sqrt(N)); 46 | expected worst-case space complexity is O(1). 47 | */ -------------------------------------------------------------------------------- /hackerrank/implementation/cutTheSticks.js: -------------------------------------------------------------------------------- 1 | function solution(A) { 2 | 3 | while (A.length) { 4 | var min = Math.min.apply(null, A) 5 | console.log(A.length) 6 | 7 | for (var i = A.length-1; i >= 0; i--) { 8 | A[i] -= min 9 | if (!A[i]) A.splice(i, 1) 10 | } 11 | } 12 | } 13 | 14 | module.exports = solution 15 | 16 | /* 17 | You are given sticks, where the length of each stick is a positive integer. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick. 18 | 19 | Suppose we have six sticks of the following lengths: 20 | 5 4 4 2 2 8 21 | 22 | Then, in one cut operation we make a cut of length 2 from each of the six sticks. For the next cut operation four sticks are left (of non-zero length), whose lengths are the following: 23 | 3 2 2 6 24 | 25 | The above step is repeated until no sticks are left. 26 | 27 | Given the length of sticks, print the number of sticks that are left before each subsequent cut operations. 28 | 29 | Note: For each cut operation, you have to recalcuate the length of smallest sticks (excluding zero-length sticks). 30 | 31 | Input Format 32 | The first line contains a single integer . 33 | The next line contains integers: a0, a1,...aN-1 separated by space, where ai represents the length of ith stick. 34 | 35 | Output Format 36 | For each operation, print the number of sticks that are cut, on separate lines. 37 | */ -------------------------------------------------------------------------------- /hackerrank/implementation/manasaAndStones-trail-difference.js: -------------------------------------------------------------------------------- 1 | function solution(input) { 2 | var A = input.split('\n') 3 | for (var k = 0; k < A.length; k++) A[k] = +A[k] 4 | 5 | for (var i = 1; i < A.length; i += 3) { 6 | var n = A[i] 7 | var a = A[i+1] 8 | var b = A[i+2] 9 | var result = [] 10 | 11 | for (var j = 0; j < n; j++) { 12 | result.push(j*b + (n-1-j)*a) 13 | } 14 | 15 | result.sort((a, b) => a - b) 16 | console.log(result.join(' ')) 17 | } 18 | } 19 | 20 | module.exports = solution 21 | 22 | /* 23 | Manasa is out on a hike with friends. She finds a trail of stones with numbers on them. She starts following the trail and notices that two consecutive stones have a difference of either or . Legend has it that there is a treasure trove at the end of the trail and if Manasa can guess the value of the last stone, the treasure would be hers. Given that the number on the first stone was , find all the possible values for the number on the last stone. 24 | 25 | Note: The numbers on the stones are in increasing order. 26 | 27 | Input Format 28 | The first line contains an integer , i.e. the number of test cases. test cases follow; each has 3 lines. The first line contains (the number of stones). The second line contains , and the third line contains . 29 | 30 | Output Format 31 | Space-separated list of numbers which are the possible values of the last stone in increasing order. 32 | */ -------------------------------------------------------------------------------- /hackerrank/implementation/sherlockAndTheBeast-3-5-decent.js: -------------------------------------------------------------------------------- 1 | function solution(N) { 2 | var fives = Math.floor(N/3) * 3 3 | var threes = N - fives 4 | 5 | while (fives) { 6 | if (threes % 5) { 7 | fives -= 3 8 | threes += 3 9 | } else { 10 | break; 11 | } 12 | } 13 | 14 | if (threes % 5) { 15 | console.log(-1) 16 | } else { 17 | console.log('5'.repeat(fives) + '3'.repeat(threes)) 18 | } 19 | } 20 | 21 | module.exports = solution 22 | 23 | /* 24 | Sherlock Holmes suspects his archenemy, Professor Moriarty, is once again plotting something diabolical. Sherlock's companion, Dr. Watson, suggests Moriarty may be responsible for MI6's recent issues with their supercomputer, The Beast. 25 | 26 | Shortly after resolving to investigate, Sherlock receives a note from Moriarty boasting about infecting The Beast with a virus; however, he also gives him a clue—a number, . Sherlock determines the key to removing the virus is to find the largest Decent Number having digits. 27 | 28 | A Decent Number has the following properties: 29 | 30 | Its digits can only be 3's and/or 5's. 31 | The number of 3's it contains is divisible by 5. 32 | The number of 5's it contains is divisible by 3. 33 | If there are more than one such number, we pick the largest one. 34 | Moriarty's virus shows a clock counting down to The Beast's destruction, and time is running out fast. Your task is to help Sherlock find the key before The Beast is destroyed! 35 | */ -------------------------------------------------------------------------------- /codility/12_euclideanAlgorithm/chocolatesByNumbers-circle-greatest-common-divisor.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function gcd(A, B) { 3 | if (!B) return A 4 | return gcd(B, A % B) 5 | } 6 | 7 | function solution(N, M) { 8 | return N / gcd(N, M) 9 | } 10 | 11 | module.exports = solution 12 | 13 | /* 14 | 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. 15 | 16 | You start to eat the chocolates. After eating a chocolate you leave only a wrapper. 17 | 18 | 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. 19 | 20 | More precisely, if you ate chocolate number X, then you will next eat the chocolate with number (X + M) modulo N (remainder of division). 21 | 22 | You stop eating when you encounter an empty wrapper. 23 | 24 | For example, given integers N = 10 and M = 4. You will eat the following chocolates: 0, 4, 8, 2, 6. 25 | 26 | The goal is to count the number of chocolates that you will eat, following the above rules. 27 | 28 | Write a function: 29 | 30 | int solution(int N, int M); 31 | that, given two positive integers N and M, returns the number of chocolates that you will eat. 32 | 33 | For example, given integers N = 10 and M = 4. the function should return 5, as explained above. 34 | 35 | Assume that: 36 | 37 | N and M are integers within the range [1..1,000,000,000]. 38 | Complexity: 39 | 40 | expected worst-case time complexity is O(log(N+M)); 41 | expected worst-case space complexity is O(log(N+M)). 42 | */ -------------------------------------------------------------------------------- /codility/09_maxSlice/maxSliceSum-max-subarray.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | var currSlice = A[0] 5 | var maxSlice = A[0] 6 | 7 | for (var i = 1; i < len; i++) { 8 | currSlice = Math.max(A[i], currSlice + A[i]) 9 | maxSlice = Math.max(currSlice, maxSlice) 10 | } 11 | 12 | return maxSlice 13 | } 14 | 15 | module.exports = solution 16 | 17 | /* 18 | 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]. 19 | 20 | Write a function: 21 | 22 | int solution(int A[], int N); 23 | that, given an array A consisting of N integers, returns the maximum sum of any slice of A. 24 | 25 | For example, given array A such that: 26 | 27 | A[0] = 3 A[1] = 2 A[2] = -6 28 | A[3] = 4 A[4] = 0 29 | the function should return 5 because: 30 | 31 | (3, 4) is a slice of A that has sum 4, 32 | (2, 2) is a slice of A that has sum −6, 33 | (0, 1) is a slice of A that has sum 5, 34 | no other slice of A has sum greater than (0, 1). 35 | Assume that: 36 | 37 | N is an integer within the range [1..1,000,000]; 38 | each element of array A is an integer within the range [−1,000,000..1,000,000]; 39 | the result will be an integer within the range [−2,147,483,648..2,147,483,647]. 40 | Complexity: 41 | 42 | expected worst-case time complexity is O(N); 43 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 44 | Elements of input arrays can be modified. 45 | */ -------------------------------------------------------------------------------- /hackerrank/dynamicProgramming/candies-neighbor-minimize.js: -------------------------------------------------------------------------------- 1 | // 66% 2 | function solution(input) { 3 | var A = input.split('\n').slice(1), i 4 | var len = A.length, i 5 | for (i = 0; i < len; i++) A[i] = +A[i] 6 | 7 | if (len <= 1) return console.log(len) 8 | 9 | var num = [] 10 | for (i = 0; i < len; i++) num.push(1) 11 | 12 | for (i = 1; i < len; i++) { 13 | if (A[i] > A[i-1]) { 14 | num[i] = num[i-1]+1 15 | } 16 | } 17 | 18 | for (i = len-1; i > 0; i--) { 19 | if (A[i-1] > A[i]) { 20 | num[i-1] = Math.max(num[i]+1, num[i-1]) 21 | } 22 | } 23 | 24 | var ret = 0 25 | for (i = 0; i < len; i++) ret += num[i] 26 | console.log(ret) 27 | } 28 | 29 | module.exports = solution 30 | 31 | /* 32 | Alice is a kindergarden teacher. She wants to give some candies to the children in her class. All the children sit in a line ( their positions are fixed), and each of them has a rating score according to his or her performance in the class. Alice wants to give at least 1 candy to each child. If two children sit next to each other, then the one with the higher rating must get more candies. Alice wants to save money, so she needs to minimize the total number of candies given to the children. 33 | 34 | Input Format 35 | 36 | The first line of the input is an integer N, the number of children in Alice's class. Each of the following N lines contains an integer that indicates the rating of each child. 37 | 38 | Constraints 39 | 40 | 1 <= N <= 10^5 41 | 1 <= ratingi <= 10^5 42 | 43 | Output Format 44 | 45 | Output a single line containing the minimum number of candies Alice must buy. 46 | */ -------------------------------------------------------------------------------- /beatmycode/theTurtlePyramid-sort.js: -------------------------------------------------------------------------------- 1 | function solution(str) { 2 | var A = str.split('\n') 3 | var N = A.length 4 | for (var i = 0; i < N; i++) A[i] = +A[i] 5 | 6 | var isSemiSorted = true 7 | var NIndex = A.indexOf(N) 8 | 9 | for (var i = NIndex; i >= 0; i--) { 10 | if (N-- !== A[i]) { 11 | isSemiSorted = false 12 | break; 13 | } 14 | } 15 | 16 | var result = isSemiSorted ? A.slice(NIndex+1) : A 17 | result.sort(function (a, b) { return b - a }) 18 | for (var i = 0; i < result.length; i++) console.log(result[i]) 19 | } 20 | 21 | /*solution("BMC_TEST_INPUT_MAGIC")*/ 22 | 23 | module.exports = solution 24 | 25 | /* 26 | Turtles would like to create a pyramid, where every turtle in the pile can only be on top of a larger turtle. The only move they can make is crawling out and then crawling on top. Since they're having a problem achieving this configuration, they ask you to write a program that can tell them in which order to move. You have to advise them, so that it takes the least amount of moves to rearrange. 27 | 28 | There are N turtles, represented by their size as numbers in the interval [1, N] (1 and N included). For example: N=3 means there are 3 turtles, and their sizes are: 1, 2, 3. 29 | 30 | The "BMC_TEST_INPUT_MAGIC" (with quotes) in the code will be replaced with the actual value of the input. The input is the current turtle stack from top to bottom, one turtle per line. The program has to output the names of whom need to move in order. First name printed will move first. 31 | 32 | Sample input: 33 | 5 34 | 1 35 | 3 36 | 2 37 | 4 38 | 39 | Sample output: 40 | 4 41 | 3 42 | 2 43 | 1 44 | */ -------------------------------------------------------------------------------- /codility/06_sorting/maxProductOfThree-max-triplet-product.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | A.sort((a, b) => a - b) 5 | 6 | return Math.max( 7 | A[0] * A[1] * A[len-1], 8 | A[len-1] * A[len-2] * A[len-3] 9 | ) 10 | } 11 | 12 | module.exports = solution 13 | 14 | /* 15 | 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). 16 | 17 | For example, array A such that: 18 | 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 | contains the following example triplets: 26 | 27 | (0, 1, 2), product is −3 * 1 * 2 = −6 28 | (1, 2, 4), product is 1 * 2 * 5 = 10 29 | (2, 4, 5), product is 2 * 5 * 6 = 60 30 | Your goal is to find the maximal product of any triplet. 31 | 32 | Write a function: 33 | 34 | int solution(int A[], int N); 35 | that, given a non-empty zero-indexed array A, returns the value of the maximal product of any triplet. 36 | 37 | For example, given array A such that: 38 | 39 | A[0] = -3 40 | A[1] = 1 41 | A[2] = 2 42 | A[3] = -2 43 | A[4] = 5 44 | A[5] = 6 45 | the function should return 60, as the product of triplet (2, 4, 5) is maximal. 46 | 47 | Assume that: 48 | 49 | N is an integer within the range [3..100,000]; 50 | each element of array A is an integer within the range [−1,000..1,000]. 51 | Complexity: 52 | 53 | expected worst-case time complexity is O(N*log(N)); 54 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments). 55 | Elements of input arrays can be modified. 56 | */ -------------------------------------------------------------------------------- /codility/04_countingElements/permCheck-permutation.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | A.sort((a, b) => a - b) 5 | 6 | for (var i = 0; i < len; i++) { 7 | if (A[i] !== i+1) return 0 8 | } 9 | 10 | return 1 11 | } 12 | 13 | module.exports = solution 14 | 15 | /* 16 | A non-empty zero-indexed array A consisting of N integers is given. 17 | 18 | A permutation is a sequence containing each element from 1 to N once, and only once. 19 | 20 | For example, array A such that: 21 | 22 | A[0] = 4 23 | A[1] = 1 24 | A[2] = 3 25 | A[3] = 2 26 | is a permutation, but array A such that: 27 | 28 | A[0] = 4 29 | A[1] = 1 30 | A[2] = 3 31 | is not a permutation, because value 2 is missing. 32 | 33 | The goal is to check whether array A is a permutation. 34 | 35 | Write a function: 36 | 37 | int solution(int A[], int N); 38 | that, given a zero-indexed array A, returns 1 if array A is a permutation and 0 if it is not. 39 | 40 | For example, given array A such that: 41 | 42 | A[0] = 4 43 | A[1] = 1 44 | A[2] = 3 45 | A[3] = 2 46 | the function should return 1. 47 | 48 | Given array A such that: 49 | 50 | A[0] = 4 51 | A[1] = 1 52 | A[2] = 3 53 | the function should return 0. 54 | 55 | Assume that: 56 | 57 | N is an integer within the range [1..100,000]; 58 | each element of array A is an integer within the range [1..1,000,000,000]. 59 | Complexity: 60 | 61 | expected worst-case time complexity is O(N); 62 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 63 | Elements of input arrays can be modified. 64 | */ -------------------------------------------------------------------------------- /codility/06_sorting/triangle-triplet-triangular.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | if (len < 3) return 0 5 | 6 | A.sort((a, b) => a - b) 7 | 8 | for (var i = 0; i < len-2; i++) { 9 | if (A[i] + A[i+1] > A[i+2]) return 1 10 | } 11 | 12 | return 0 13 | } 14 | 15 | module.exports = solution 16 | 17 | /* 18 | 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: 19 | 20 | A[P] + A[Q] > A[R], 21 | A[Q] + A[R] > A[P], 22 | A[R] + A[P] > A[Q]. 23 | For example, consider array A such that: 24 | 25 | A[0] = 10 A[1] = 2 A[2] = 5 26 | A[3] = 1 A[4] = 8 A[5] = 20 27 | Triplet (0, 2, 4) is triangular. 28 | 29 | Write a function: 30 | 31 | int solution(int A[], int N); 32 | 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. 33 | 34 | For example, given array A such that: 35 | 36 | A[0] = 10 A[1] = 2 A[2] = 5 37 | A[3] = 1 A[4] = 8 A[5] = 20 38 | the function should return 1, as explained above. Given array A such that: 39 | 40 | A[0] = 10 A[1] = 50 A[2] = 5 41 | A[3] = 1 42 | the function should return 0. 43 | 44 | Assume that: 45 | 46 | N is an integer within the range [0..100,000]; 47 | each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]. 48 | Complexity: 49 | 50 | expected worst-case time complexity is O(N*log(N)); 51 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 52 | Elements of input arrays can be modified. 53 | */ -------------------------------------------------------------------------------- /hackerrank/implementation/acmIcpcTeam-topics.js: -------------------------------------------------------------------------------- 1 | function solution(N, M, A) { 2 | var maxForOneTeam = 0 3 | var maxTeams = 0 4 | 5 | for (var i = 0; i < N-1; i++) { 6 | for (var j = i+1; j < N; j++) { 7 | var topics = 0 8 | 9 | for (var k = 0; k < M; k++) { 10 | if (A[i][k] === '1' || A[j][k] === '1') topics++ 11 | } 12 | 13 | if (topics > maxForOneTeam) { 14 | maxForOneTeam = topics 15 | maxTeams = 1 16 | } else if (topics === maxForOneTeam) { 17 | maxTeams++ 18 | } 19 | } 20 | } 21 | 22 | console.log(maxForOneTeam) 23 | console.log(maxTeams) 24 | } 25 | 26 | module.exports = solution 27 | 28 | /* 29 | You are given a list of people who are attending ACM-ICPC World Finals. Each of them are either well versed in a topic or they are not. Find out the maximum number of topics a 2-person team can know. And also find out how many teams can know that maximum number of topics. 30 | 31 | Note Suppose a, b, and c are three different people, then (a,b) and (b,c) are counted as two different teams. 32 | 33 | Input Format 34 | 35 | The first line contains two integers, and , separated by a single space, where represents the number of people, and represents the number of topics. lines follow. 36 | Each line contains a binary string of length . If the th line's th character is , then the th person knows the th topic; otherwise, he doesn't know the topic. 37 | 38 | Constraints 39 | 40 | 41 | Output Format 42 | 43 | On the first line, print the maximum number of topics a 2-person team can know. 44 | On the second line, print the number of 2-person teams that can know the maximum number of topics. 45 | */ -------------------------------------------------------------------------------- /hackerrank/search/iceCreamParlor.js: -------------------------------------------------------------------------------- 1 | function solution(input) { 2 | input = input.split('\n') 3 | for (var k = 1; k < input.length; k += 3) { 4 | var M = input[k] 5 | var A = input[k+2].split(' ') 6 | var len = A.length 7 | for (var i = 0; i < len; i++) A[i] = +A[i] 8 | 9 | var items = {} 10 | for (var i = 0; i < len; i++) { 11 | items[A[i]] = items[A[i]] || [] 12 | items[A[i]].push(i) 13 | } 14 | 15 | for (var i = 0; i < len; i++) { 16 | var target = items[M-A[i]] 17 | 18 | if (target && (target[0] !== i || target[1] !== i)) { 19 | var first = i+1 20 | var second = target[0] === i ? target[1]+1 : target[0]+1 21 | break; 22 | } 23 | } 24 | 25 | console.log(first < second ? first+' '+second : second+' '+first) 26 | } 27 | } 28 | 29 | module.exports = solution 30 | 31 | /* 32 | Sunny and Johnny together have dollars they want to spend on ice cream. The parlor offers flavors, and they want to choose two flavors so that they end up spending the whole amount. 33 | 34 | You are given the cost of these flavors. The cost of the flavor is denoted by . You have to display the indices of the two flavors whose sum is . 35 | 36 | Input Format 37 | 38 | The first line of the input contains ; test cases follow. 39 | Each test case follows the format detailed below: The first line contains . The second line contains . The third line contains space-separated integers denoting the price of each flavor. Here, the integer denotes . 40 | 41 | Output Format 42 | 43 | Output two integers, each of which is a valid index of a flavor. The lower index must be printed first. Indices are indexed from to . 44 | */ -------------------------------------------------------------------------------- /hackerrank/implementation/lisasWorkbook-page-chapters.js: -------------------------------------------------------------------------------- 1 | function solution(input) { 2 | var N = +input.split('\n')[0].split(' ')[0] 3 | var K = +input.split('\n')[0].split(' ')[1] 4 | var A = input.split('\n')[1].split(' ') 5 | for (var a = 0; a < A.length; a++) A[a] = +A[a] 6 | 7 | var count = 0 8 | var page = 0 9 | 10 | for (var i = 0; i < A.length; i++) { 11 | page++ 12 | var p 13 | 14 | for (var j = 1; j <= A[i]; j++) { 15 | p = Math.ceil(j/K) - 1 16 | if (page+p === j) count++ 17 | } 18 | 19 | page += p 20 | } 21 | 22 | console.log(count) 23 | } 24 | 25 | module.exports = solution 26 | 27 | /* 28 | isa just got a new math workbook. A workbook contains exercise problems, grouped into chapters. 29 | 30 | There are chapters in Lisa's workbook, numbered from to . 31 | The -th chapter has problems, numbered from to . 32 | Each page can hold up to problems. There are no empty pages or unnecessary spaces, so only the last page of a chapter may contain fewer than problems. 33 | Each new chapter starts on a new page, so a page will never contain problems from more than one chapter. 34 | The page number indexing starts at . 35 | Lisa believes a problem to be special if its index (within a chapter) is the same as the page number where it's located. Given the details for Lisa's workbook, can you count its number of special problems? 36 | 37 | Note: See the diagram in the Explanation section for more details. 38 | 39 | Input Format 40 | 41 | The first line contains two integers and — the number of chapters and the maximum number of problems per page respectively. 42 | The second line contains integers , where denotes the number of problems in the -th chapter. 43 | */ -------------------------------------------------------------------------------- /codility/15_caterpillarMethod/absDistinct-absolute-unique.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | var uniq = {} 5 | var size = 0 6 | 7 | for (var i = 0; i < len; i++) { 8 | var abs = Math.abs(A[i]) 9 | if (!uniq[abs]) { 10 | uniq[abs] = true 11 | size++ 12 | } 13 | } 14 | 15 | return size 16 | } 17 | 18 | module.exports = solution 19 | 20 | /* 21 | 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. 22 | 23 | For example, consider array A such that: 24 | 25 | A[0] = -5 26 | A[1] = -3 27 | A[2] = -1 28 | A[3] = 0 29 | A[4] = 3 30 | A[5] = 6 31 | 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. 32 | 33 | Write a function: 34 | 35 | int solution(int A[], int N); 36 | that, given a non-empty zero-indexed array A consisting of N numbers, returns absolute distinct count of array A. 37 | 38 | For example, given array A such that: 39 | 40 | A[0] = -5 41 | A[1] = -3 42 | A[2] = -1 43 | A[3] = 0 44 | A[4] = 3 45 | A[5] = 6 46 | the function should return 5, as explained above. 47 | 48 | Assume that: 49 | 50 | N is an integer within the range [1..100,000]; 51 | each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]; 52 | array A is sorted in non-decreasing order. 53 | Complexity: 54 | 55 | expected worst-case time complexity is O(N); 56 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 57 | Elements of input arrays can be modified. 58 | */ -------------------------------------------------------------------------------- /hackerrank/strings/palindromeIndex-string.js: -------------------------------------------------------------------------------- 1 | function solution(input) { 2 | input = input.split('\n').slice(1) 3 | 4 | function isPalindrome(S) { 5 | var len = S.length 6 | for (var i = 0; i < len; i++) { 7 | if (S[i] !== S[len-i-1]) return false 8 | } 9 | return true 10 | } 11 | 12 | for (var k = 0; k < input.length; k++) { 13 | var S = input[k] 14 | var len = S.length 15 | 16 | if (isPalindrome(S)) { 17 | console.log(-1) 18 | } else { 19 | for (var i = 0; i < len; i++) { 20 | var j = len-i-1 21 | if (S[i] !== S[j]) { 22 | if (isPalindrome(S.slice(0, i) + S.slice(i+1))) { 23 | console.log(i) 24 | break; 25 | } else if (isPalindrome(S.slice(0, j) + S.slice(j+1))) { 26 | console.log(j) 27 | break; 28 | } else { 29 | console.log(-1) 30 | break; 31 | } 32 | } 33 | } 34 | } 35 | } 36 | } 37 | 38 | module.exports = solution 39 | 40 | /* 41 | Given a string, , of lowercase letters, determine the index of the character whose removal will make a palindrome. If is already a palindrome or no such character exists, then print . There will always be a valid solution, and any correct answer is acceptable. For example, if "bcbc", we can either remove 'b' at index or 'c' at index . 42 | 43 | Input Format 44 | 45 | The first line contains an integer, , denoting the number of test cases. 46 | Each line of the subsequent lines (where ) describes a test case in the form of a single string, . 47 | 48 | Constraints 49 | 50 | All characters are lowercase English letters. 51 | Output Format 52 | 53 | Print an integer denoting the zero-indexed position of the character that makes not a palindrome; if is already a palindrome or no such character exists, print . 54 | */ -------------------------------------------------------------------------------- /codility/05_prefixSums/passingCars.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | var pairs = 0 5 | var westCount = 0 6 | 7 | for (var i = len-1; i >= 0; i--) { 8 | A[i] ? westCount++ : pairs += westCount 9 | if (pairs > 1000000000) return -1 10 | } 11 | 12 | return pairs 13 | } 14 | 15 | module.exports = solution 16 | 17 | /* 18 | 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. 19 | 20 | Array A contains only 0s and/or 1s: 21 | 22 | 0 represents a car traveling east, 23 | 1 represents a car traveling west. 24 | 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. 25 | 26 | For example, consider array A such that: 27 | 28 | A[0] = 0 29 | A[1] = 1 30 | A[2] = 0 31 | A[3] = 1 32 | A[4] = 1 33 | We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4). 34 | 35 | Write a function: 36 | 37 | int solution(int A[], int N); 38 | that, given a non-empty zero-indexed array A of N integers, returns the number of pairs of passing cars. 39 | 40 | The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000. 41 | 42 | For example, given: 43 | 44 | A[0] = 0 45 | A[1] = 1 46 | A[2] = 0 47 | A[3] = 1 48 | A[4] = 1 49 | the function should return 5, as explained above. 50 | 51 | Assume that: 52 | 53 | N is an integer within the range [1..100,000]; 54 | each element of array A is an integer that can have one of the following values: 0, 1. 55 | Complexity: 56 | 57 | expected worst-case time complexity is O(N); 58 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments). 59 | Elements of input arrays can be modified. 60 | */ -------------------------------------------------------------------------------- /codility/15_caterpillarMethod/countTriangles-triplet.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | if (len < 3) return 0 5 | A.sort((a, b) => a - b) 6 | var count = 0 7 | 8 | for (var i = 0; i < len-2; i++) { 9 | for (var j = i+1; j < len-1; j++) { 10 | for (var k = j+1; k < len; k++) { 11 | if (A[i] + A[j] > A[k]) { 12 | count++ 13 | } else { 14 | break; 15 | } 16 | } 17 | } 18 | } 19 | 20 | return count 21 | } 22 | 23 | module.exports = solution 24 | 25 | /* 26 | A zero-indexed array A consisting of N integers is given. A triplet (P, Q, R) is triangular if it is possible to build a triangle with sides of lengths A[P], A[Q] and A[R]. In other words, triplet (P, Q, R) is triangular if 0 ≤ P < Q < R < N and: 27 | 28 | A[P] + A[Q] > A[R], 29 | A[Q] + A[R] > A[P], 30 | A[R] + A[P] > A[Q]. 31 | For example, consider array A such that: 32 | 33 | A[0] = 10 A[1] = 2 A[2] = 5 34 | A[3] = 1 A[4] = 8 A[5] = 12 35 | 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). 36 | 37 | Write a function: 38 | 39 | int solution(int A[], int N); 40 | that, given a zero-indexed array A consisting of N integers, returns the number of triangular triplets in this array. 41 | 42 | For example, given array A such that: 43 | 44 | A[0] = 10 A[1] = 2 A[2] = 5 45 | A[3] = 1 A[4] = 8 A[5] = 12 46 | the function should return 4, as explained above. 47 | 48 | Assume that: 49 | 50 | N is an integer within the range [0..1,000]; 51 | each element of array A is an integer within the range [1..1,000,000,000]. 52 | Complexity: 53 | 54 | expected worst-case time complexity is O(N2); 55 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 56 | Elements of input arrays can be modified. 57 | */ -------------------------------------------------------------------------------- /codility/07_stacksAndQueues/brackets-nested-nesting.js: -------------------------------------------------------------------------------- 1 | // 87% 2 | function solution(S) { 3 | var lastLen 4 | 5 | while (lastLen !== S.length) { 6 | lastLen = S.length 7 | S = S.replace(/\(\)|\[\]|\{\}/g, '') 8 | } 9 | 10 | return S.length ? 0 : 1 11 | } 12 | 13 | // 100% 14 | function solution(S) { 15 | var len = S.length 16 | var openers = [] 17 | 18 | if (len % 2 === 1 || /\(\[\{/.test(S[len-1])) return 0 19 | 20 | for (var i = 0; i < len; i++) { 21 | 22 | if (S[i] === '(' || S[i] === '[' || S[i] === '{') { 23 | openers.push(S[i]) 24 | } else { 25 | var lastOpener = openers.pop() 26 | if ((lastOpener === '(' && S[i] !== ')') || 27 | (lastOpener === '[' && S[i] !== ']') || 28 | (lastOpener === '{' && S[i] !== '}')) { 29 | 30 | return 0 31 | } 32 | } 33 | } 34 | 35 | return openers.length ? 0 : 1 36 | } 37 | 38 | module.exports = solution 39 | 40 | /* 41 | A string S consisting of N characters is considered to be properly nested if any of the following conditions is true: 42 | 43 | S is empty; 44 | S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string; 45 | S has the form "VW" where V and W are properly nested strings. 46 | For example, the string "{[()()]}" is properly nested but "([)()]" is not. 47 | 48 | Write a function: 49 | 50 | int solution(char *S); 51 | that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise. 52 | 53 | For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above. 54 | 55 | Assume that: 56 | 57 | N is an integer within the range [0..200,000]; 58 | string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")". 59 | Complexity: 60 | 61 | expected worst-case time complexity is O(N); 62 | expected worst-case space complexity is O(N) (not counting the storage required for input arguments). 63 | */ -------------------------------------------------------------------------------- /beatmycode/circularPrimes-rotation.js: -------------------------------------------------------------------------------- 1 | function getPrimes(N) { 2 | var i, p = 1 3 | var range = [] 4 | for (i = 0; i <= N; i++) range.push(true) 5 | 6 | while (p*p <= N) { 7 | if (!range[++p]) continue; 8 | for (i = p*p; i <= N; i += p) range[i] = false 9 | } 10 | 11 | var primes = [] 12 | for (i = 2; i <= N; i++) { 13 | if (range[i]) { 14 | var str = i.toString() 15 | if (str.indexOf('0') < 0) primes.push(str) 16 | } 17 | } 18 | 19 | return primes 20 | } 21 | 22 | function getRotations(num) { 23 | var results = [num] 24 | for (var i = 1; i < num.length; i++) { 25 | var temp = num 26 | num = num.slice(1) + temp[0] 27 | results.push(num) 28 | } 29 | return results 30 | } 31 | 32 | function solution(str) { 33 | var primes = getPrimes(+(str+'0')-1) 34 | var len = primes.length 35 | var primesObj = {} 36 | var i, j 37 | for (i = 0; i < len; i++) primesObj[primes[i]] = true 38 | 39 | var count = 0 40 | 41 | var N = +str-1 42 | for (i = 0; i < len; i++) { 43 | if (primes[i] > N) break; 44 | var rotations = getRotations(primes[i]) 45 | var areCircular = true 46 | 47 | for (j = 0; j < rotations.length; j++) { 48 | if (!primesObj[rotations[j]]) areCircular = false 49 | } 50 | 51 | if (areCircular) count++ 52 | } 53 | 54 | console.log(count) 55 | } 56 | 57 | /*solution("BMC_TEST_INPUT_MAGIC")*/ 58 | 59 | module.exports = solution 60 | 61 | /* 62 | A number is called a circular prime if all of its rotations (rotations of their digits) are primes themselves. 63 | 64 | For example the prime number 197 has two rotations: 971, and 719. Both of them are prime, so all of them are circular primes. 65 | 66 | There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. 67 | 68 | How many circular primes are there below N if 1 <= N <= 1000000? 69 | 70 | The "BMC_TEST_INPUT_MAGIC" (with quotes) in the code will be replaced with the actual value of the input. 71 | */ -------------------------------------------------------------------------------- /codility/01_iterations/binaryGap-repeating-consecutive.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(N) { 3 | var binary = (N >>> 0).toString(2) 4 | var regex = /1(0+)(?=1)/g 5 | var matches 6 | var gaps = [] 7 | 8 | while (matches = regex.exec(binary)) { 9 | gaps.push(matches[1]) 10 | } 11 | 12 | return gaps.length ? Math.max.apply(null, gaps.map(str => str.length)) : 0 13 | } 14 | 15 | // 100% 16 | function solution2(N) { 17 | var binary = (N >>> 0).toString(2) 18 | var gap = 0 19 | var gaps = [] 20 | var oneDetected = false 21 | 22 | binary.split('').forEach(val => { 23 | if (val === '0') { 24 | if (oneDetected) gap++ 25 | } else { 26 | if (gap) gaps.push(gap) 27 | gap = 0 28 | oneDetected = true 29 | } 30 | }) 31 | 32 | return gaps.length ? Math.max.apply(null, gaps) : 0 33 | } 34 | 35 | module.exports = solution 36 | 37 | /* 38 | A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. 39 | 40 | For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. 41 | 42 | Write a function: 43 | 44 | int solution(int N); 45 | that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap. 46 | 47 | For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. 48 | 49 | Assume that: 50 | 51 | N is an integer within the range [1..2,147,483,647]. 52 | Complexity: 53 | 54 | expected worst-case time complexity is O(log(N)); 55 | expected worst-case space complexity is O(1). 56 | */ -------------------------------------------------------------------------------- /codility/02_arrays/oddOccurrencesInArray.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | A.sort((a, b) => a-b) 4 | 5 | var len = A.length 6 | var count = 0 7 | 8 | for (var i = 0; i < len; i++) { 9 | A[i] === A[i-1] ? count++ : count = 1 10 | 11 | if (count%2 === 1 && A[i] !== A[i+1]) { 12 | return A[i] 13 | } 14 | } 15 | } 16 | 17 | // 100% 18 | function solution(A) { 19 | var len = A.length 20 | var ret = A[0] 21 | 22 | for (var i = 1; i < len; i++) { 23 | ret ^= A[i] 24 | } 25 | 26 | return ret 27 | } 28 | 29 | module.exports = solution 30 | 31 | /* 32 | A non-empty zero-indexed array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired. 33 | 34 | For example, in array A such that: 35 | 36 | A[0] = 9 A[1] = 3 A[2] = 9 37 | A[3] = 3 A[4] = 9 A[5] = 7 38 | A[6] = 9 39 | the elements at indexes 0 and 2 have value 9, 40 | the elements at indexes 1 and 3 have value 3, 41 | the elements at indexes 4 and 6 have value 9, 42 | the element at index 5 has value 7 and is unpaired. 43 | Write a function: 44 | 45 | int solution(int A[], int N); 46 | that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element. 47 | 48 | For example, given array A such that: 49 | 50 | A[0] = 9 A[1] = 3 A[2] = 9 51 | A[3] = 3 A[4] = 9 A[5] = 7 52 | A[6] = 9 53 | the function should return 7, as explained in the example above. 54 | 55 | Assume that: 56 | 57 | N is an odd integer within the range [1..1,000,000]; 58 | each element of array A is an integer within the range [1..1,000,000,000]; 59 | all but one of the values in A occur an even number of times. 60 | Complexity: 61 | 62 | expected worst-case time complexity is O(N); 63 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments). 64 | Elements of input arrays can be modified. 65 | */ -------------------------------------------------------------------------------- /codility/07_stacksAndQueues/stoneWall-minimum-blocks-manhattan-skyline.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(H) { 3 | var len = H.length 4 | var stack = [] 5 | var count = 0 6 | 7 | for (var i = 0; i < len; i++) { 8 | while (stack.length && stack[stack.length-1] > H[i]) stack.pop() 9 | 10 | if (!stack.length || stack[stack.length-1] < H[i]) { 11 | stack.push(H[i]) 12 | count++ 13 | } 14 | } 15 | 16 | return count 17 | } 18 | 19 | module.exports = solution 20 | 21 | /* 22 | Solution to this task can be found at our blog. 23 | 24 | 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. 25 | 26 | 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. 27 | 28 | Write a function: 29 | 30 | int solution(int H[], int N); 31 | 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. 32 | 33 | For example, given array H containing N = 9 integers: 34 | 35 | H[0] = 8 H[1] = 8 H[2] = 5 36 | H[3] = 7 H[4] = 9 H[5] = 8 37 | H[6] = 7 H[7] = 4 H[8] = 8 38 | the function should return 7. The figure shows one possible arrangement of seven blocks. 39 | 40 | Assume that: 41 | 42 | N is an integer within the range [1..100,000]; 43 | each element of array H is an integer within the range [1..1,000,000,000]. 44 | Complexity: 45 | 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 | */ -------------------------------------------------------------------------------- /beatmycode/minesweeper-matrix.js: -------------------------------------------------------------------------------- 1 | function solution(str) { 2 | var rows = str.split('\n') 3 | var i, j 4 | 5 | for (i = 0; i < rows.length; i++) { 6 | rows[i] = rows[i].split(' ') 7 | rows[i].unshift('O') 8 | rows[i].push('O') 9 | } 10 | 11 | rows.unshift([]) 12 | rows.push([]) 13 | for (i = 0; i < rows[1].length; i++) { 14 | rows[0].push('O') 15 | rows[rows.length-1].push('O') 16 | } 17 | 18 | var ret = '' 19 | for (i = 1; i < rows.length-1; i++) { 20 | var row = '' 21 | 22 | for (j = 1; j < rows[i].length-1; j++) { 23 | if (rows[i][j] === 'X') { 24 | var count = 'X' 25 | } else { 26 | var count = 0 27 | if (rows[i-1][j-1] === 'X') count++ 28 | if (rows[i-1][j] === 'X') count++ 29 | if (rows[i-1][j+1] === 'X') count++ 30 | if (rows[i][j-1] === 'X') count++ 31 | if (rows[i][j+1] === 'X') count++ 32 | if (rows[i+1][j-1] === 'X') count++ 33 | if (rows[i+1][j] === 'X') count++ 34 | if (rows[i+1][j+1] === 'X') count++ 35 | } 36 | row += j === rows[i].length-2 ? count : count+' ' 37 | } 38 | ret += i === rows.length-2 ? row : row+'\n' 39 | } 40 | console.log(ret) 41 | } 42 | 43 | /*solution("BMC_TEST_INPUT_MAGIC")*/ 44 | 45 | module.exports = solution 46 | 47 | /* 48 | Calculate the number of mines in the surrounding cells for every cell in the field. 49 | 50 | The "BMC_TEST_INPUT_MAGIC" (with quotes) in the code will be replaced with the actual value of the input. 51 | 52 | Input format: Columns are separated by spaces, rows are separated by newlines ("\n"). "X" marks a mine, "O" marks a mine-free field. 53 | 54 | Output format: "X" fields are to be left as they are. For every field containing "O", you are to calculate the number of mines surrounding that field. 55 | 56 | Sample input: 57 | O O O O X O O O O O 58 | X X O O O O O O X O 59 | O O O O O O O O O O 60 | O O O O O O O O O O 61 | O O O O O X O O O O 62 | 63 | Sample output: 64 | 2 2 1 1 X 1 0 1 1 1 65 | X X 1 1 1 1 0 1 X 1 66 | 2 2 1 0 0 0 0 1 1 1 67 | 0 0 0 0 1 1 1 0 0 0 68 | 0 0 0 0 1 X 1 0 0 0 69 | */ 70 | -------------------------------------------------------------------------------- /codility/03_timeComplexity/tapeEquilibrium-minimal-absolute-sum-difference.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length, 4 | sums = {}, 5 | result = Infinity 6 | 7 | for (var i = 1; i < len; i++) { 8 | 9 | sums[i] = sums[i] || { prev: 0, next: 0} 10 | sums[i].prev = sums[i-1] ? sums[i-1].prev + A[i-1] : A[i-1] 11 | 12 | var j = len-i 13 | 14 | sums[j] = sums[j] || { prev: 0, next: 0} 15 | sums[j].next = sums[j+1] ? sums[j+1].next + A[j] : A[j] 16 | } 17 | 18 | for (var key in sums) { 19 | var abs = Math.abs(sums[key].prev - sums[key].next) 20 | result = abs < result ? abs : result 21 | } 22 | 23 | return result 24 | } 25 | 26 | module.exports = solution 27 | 28 | /* 29 | A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape. 30 | 31 | 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]. 32 | 33 | 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])| 34 | 35 | In other words, it is the absolute difference between the sum of the first part and the sum of the second part. 36 | 37 | For example, consider array A such that: 38 | 39 | A[0] = 3 40 | A[1] = 1 41 | A[2] = 2 42 | A[3] = 4 43 | A[4] = 3 44 | We can split this tape in four places: 45 | 46 | P = 1, difference = |3 − 10| = 7 47 | P = 2, difference = |4 − 9| = 5 48 | P = 3, difference = |6 − 7| = 1 49 | P = 4, difference = |10 − 3| = 7 50 | Write a function: 51 | 52 | int solution(int A[], int N); 53 | that, given a non-empty zero-indexed array A of N integers, returns the minimal difference that can be achieved. 54 | 55 | For example, given: 56 | 57 | A[0] = 3 58 | A[1] = 1 59 | A[2] = 2 60 | A[3] = 4 61 | A[4] = 3 62 | the function should return 1, as explained above. 63 | 64 | Assume that: 65 | 66 | N is an integer within the range [2..100,000]; 67 | each element of array A is an integer within the range [−1,000..1,000]. 68 | Complexity: 69 | 70 | expected worst-case time complexity is O(N); 71 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 72 | Elements of input arrays can be modified. 73 | */ -------------------------------------------------------------------------------- /codility/09_maxSlice/maxProfit-max-subarray.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | var currProfit = 0 5 | var maxProfit = 0 6 | var maxExit = A[len-1] 7 | 8 | for (var i = len-2; i >= 0; i--) { 9 | currProfit = maxExit - A[i] 10 | maxProfit = Math.max(maxProfit, currProfit) 11 | maxExit = Math.max(maxExit, A[i]) 12 | } 13 | 14 | return maxProfit 15 | } 16 | 17 | module.exports = solution 18 | 19 | /* 20 | 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]. 21 | 22 | For example, consider the following array A consisting of six elements such that: 23 | 24 | A[0] = 23171 25 | A[1] = 21011 26 | A[2] = 21123 27 | A[3] = 21366 28 | A[4] = 21013 29 | A[5] = 21367 30 | 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. 31 | 32 | Write a function, 33 | 34 | int solution(int A[], int N); 35 | 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. 36 | 37 | For example, given array A consisting of six elements such that: 38 | 39 | A[0] = 23171 40 | A[1] = 21011 41 | A[2] = 21123 42 | A[3] = 21366 43 | A[4] = 21013 44 | A[5] = 21367 45 | the function should return 356, as explained above. 46 | 47 | Assume that: 48 | 49 | N is an integer within the range [0..400,000]; 50 | each element of array A is an integer within the range [0..200,000]. 51 | Complexity: 52 | 53 | expected worst-case time complexity is O(N); 54 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments). 55 | Elements of input arrays can be modified. 56 | */ -------------------------------------------------------------------------------- /codility/15_caterpillarMethod/countDistinctSlices-unique.js: -------------------------------------------------------------------------------- 1 | // 70% - THIS IS O(N2) - TOO SLOW 2 | function solution(M, A) { 3 | var len = A.length 4 | var sliceCount = A.length 5 | 6 | for (var i = 0; i < len-1; i++) { 7 | var count = 0 8 | var uniq = {} 9 | uniq[A[i]] = true 10 | 11 | for (var j = i+1; j < len; j++) { 12 | if (uniq[A[j]]) break; 13 | uniq[A[j]] = true 14 | count++ 15 | } 16 | 17 | sliceCount += count 18 | if (sliceCount > 1000000000) return 1000000000 19 | } 20 | 21 | return sliceCount 22 | } 23 | 24 | module.exports = solution 25 | 26 | /* 27 | 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. 28 | 29 | 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. 30 | 31 | For example, consider integer M = 6 and array A such that: 32 | 33 | A[0] = 3 34 | A[1] = 4 35 | A[2] = 5 36 | A[3] = 5 37 | A[4] = 2 38 | 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). 39 | 40 | The goal is to calculate the number of distinct slices. 41 | 42 | Write a function: 43 | 44 | int solution(int M, int A[], int N); 45 | that, given an integer M and a non-empty zero-indexed array A consisting of N integers, returns the number of distinct slices. 46 | 47 | If the number of distinct slices is greater than 1,000,000,000, the function should return 1,000,000,000. 48 | 49 | For example, given integer M = 6 and array A such that: 50 | 51 | A[0] = 3 52 | A[1] = 4 53 | A[2] = 5 54 | A[3] = 5 55 | A[4] = 2 56 | the function should return 9, as explained above. 57 | 58 | Assume that: 59 | 60 | N is an integer within the range [1..100,000]; 61 | M is an integer within the range [0..100,000]; 62 | each element of array A is an integer within the range [0..M]. 63 | Complexity: 64 | 65 | expected worst-case time complexity is O(N); 66 | expected worst-case space complexity is O(M), beyond input storage (not counting the storage required for input arguments). 67 | Elements of input arrays can be modified. 68 | */ -------------------------------------------------------------------------------- /codility/16_greedyAlgorithms/maxNonoverlappingSegments-common-point.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A, B) { 3 | var len = A.length 4 | if (!len) return 0 5 | var count = 1 6 | var last = 0 7 | 8 | for (var i = 1; i < len; i++) { 9 | if (A[i] > B[last]) { 10 | count++ 11 | last = i 12 | } 13 | } 14 | 15 | return count 16 | } 17 | 18 | module.exports = solution 19 | 20 | /* 21 | Located on a line are N segments, numbered from 0 to N − 1, whose positions are given in zero-indexed arrays A and B. For each I (0 ≤ I < N) the position of segment I is from A[I] to B[I] (inclusive). The segments are sorted by their ends, which means that B[K] ≤ B[K + 1] for K such that 0 ≤ K < N − 1. 22 | 23 | Two segments I and J, such that I ≠ J, are overlapping if they share at least one common point. In other words, A[I] ≤ A[J] ≤ B[I] or A[J] ≤ A[I] ≤ B[J]. 24 | 25 | We say that the set of segments is non-overlapping if it contains no two overlapping segments. The goal is to find the size of a non-overlapping set containing the maximal number of segments. 26 | 27 | For example, consider arrays A, B such that: 28 | 29 | A[0] = 1 B[0] = 5 30 | A[1] = 3 B[1] = 6 31 | A[2] = 7 B[2] = 8 32 | A[3] = 9 B[3] = 9 33 | A[4] = 9 B[4] = 10 34 | The segments are shown in the figure below. 35 | 36 | 37 | 38 | The size of a non-overlapping set containing a maximal number of segments is 3. For example, possible sets are {0, 2, 3}, {0, 2, 4}, {1, 2, 3} or {1, 2, 4}. There is no non-overlapping set with four segments. 39 | 40 | Write a function: 41 | 42 | int solution(int A[], int B[], int N); 43 | that, given two zero-indexed arrays A and B consisting of N integers, returns the size of a non-overlapping set containing a maximal number of segments. 44 | 45 | For example, given arrays A, B shown above, the function should return 3, as explained above. 46 | 47 | Assume that: 48 | 49 | N is an integer within the range [0..30,000]; 50 | each element of arrays A, B is an integer within the range [0..1,000,000,000]; 51 | A[I] ≤ B[I], for each I (0 ≤ I < N); 52 | B[K] ≤ B[K + 1], for each K (0 ≤ K < N − 1). 53 | Complexity: 54 | 55 | expected worst-case time complexity is O(N); 56 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 57 | Elements of input arrays can be modified. 58 | */ -------------------------------------------------------------------------------- /codility/16_greedyAlgorithms/tieRopes-adjacent.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(K, A) { 3 | var len = A.length 4 | var sum = 0 5 | var count = 0 6 | 7 | for (var i = 0; i < len; i++) { 8 | sum += A[i] 9 | if (sum >= K) { 10 | count++ 11 | sum = 0 12 | } 13 | } 14 | 15 | return count 16 | } 17 | 18 | module.exports = solution 19 | 20 | /* 21 | 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]. 22 | 23 | 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. 24 | 25 | 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. 26 | 27 | For example, consider K = 4 and array A such that: 28 | 29 | A[0] = 1 30 | A[1] = 2 31 | A[2] = 3 32 | A[3] = 4 33 | A[4] = 1 34 | A[5] = 1 35 | A[6] = 3 36 | The ropes are shown in the figure below. 37 | 38 | 39 | 40 | We can tie: 41 | 42 | rope 1 with rope 2 to produce a rope of length A[1] + A[2] = 5; 43 | rope 4 with rope 5 with rope 6 to produce a rope of length A[4] + A[5] + A[6] = 5. 44 | 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. 45 | 46 | Write a function: 47 | 48 | int solution(int K, int A[], int N); 49 | 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. 50 | 51 | For example, given K = 4 and array A such that: 52 | 53 | A[0] = 1 54 | A[1] = 2 55 | A[2] = 3 56 | A[3] = 4 57 | A[4] = 1 58 | A[5] = 1 59 | A[6] = 3 60 | the function should return 3, as explained above. 61 | 62 | Assume that: 63 | 64 | N is an integer within the range [1..100,000]; 65 | K is an integer within the range [1..1,000,000,000]; 66 | each element of array A is an integer within the range [1..1,000,000,000]. 67 | Complexity: 68 | 69 | expected worst-case time complexity is O(N); 70 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 71 | Elements of input arrays can be modified. 72 | */ -------------------------------------------------------------------------------- /codility/12_euclideanAlgorithm/commonPrimeDivisors-prime-factorization.js: -------------------------------------------------------------------------------- 1 | // 92% 2 | function primeFactors(N) { 3 | var primeFactors = {} 4 | var notDone = 1 < N 5 | 6 | while (notDone) { 7 | var P = 2 8 | var base = Math.sqrt(N) 9 | 10 | if (N % P) { 11 | P = 3 12 | while (N % P && P < base) P += 2 13 | } 14 | 15 | P = P > base ? N : P 16 | primeFactors[P] = P 17 | 18 | notDone = P !== N 19 | N = N / P 20 | } 21 | 22 | return primeFactors 23 | } 24 | 25 | function solution(A, B) { 26 | var len = A.length 27 | var count = 0 28 | 29 | for (var i = 0; i < len; i++) { 30 | var fA = primeFactors(A[i]) 31 | var fB = primeFactors(B[i]) 32 | if (JSON.stringify(fA) === JSON.stringify(fB)) count++ 33 | } 34 | 35 | return count 36 | } 37 | 38 | module.exports = solution 39 | 40 | /* 41 | 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. 42 | 43 | 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. 44 | 45 | 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. 46 | 47 | For example, given: 48 | 49 | N = 15 and M = 75, the prime divisors are the same: {3, 5}; 50 | N = 10 and M = 30, the prime divisors aren't the same: {2, 5} is not equal to {2, 3, 5}; 51 | N = 9 and M = 5, the prime divisors aren't the same: {3} is not equal to {5}. 52 | Write a function: 53 | 54 | int solution(int A[], int B[], int Z); 55 | 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. 56 | 57 | For example, given: 58 | 59 | A[0] = 15 B[0] = 75 60 | A[1] = 10 B[1] = 30 61 | A[2] = 3 B[2] = 5 62 | the function should return 1, because only one pair (15, 75) has the same set of prime divisors. 63 | 64 | Assume that: 65 | 66 | Z is an integer within the range [1..6,000]; 67 | each element of arrays A, B is an integer within the range [1..2,147,483,647]. 68 | Complexity: 69 | 70 | expected worst-case time complexity is O(Z*log(max(A)+max(B))2); 71 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments). 72 | Elements of input arrays can be modified. 73 | */ -------------------------------------------------------------------------------- /codility/05_prefixSums/minAvgTwoSlice.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | var min = Infinity 5 | var minPos = 0 6 | 7 | for (var i = 0; i < len; i++) { 8 | 9 | if (typeof A[i+2] !== 'undefined') { 10 | var slice3 = (A[i] + A[i+1] + A[i+2]) / 3 11 | if (min > slice3) { 12 | minPos = i 13 | min = slice3 14 | } 15 | } 16 | 17 | if (typeof A[i+1] !== 'undefined') { 18 | var slice2 = (A[i] + A[i+1]) / 2 19 | if (min > slice2) { 20 | minPos = i 21 | min = slice2 22 | } 23 | } 24 | } 25 | 26 | return minPos 27 | } 28 | 29 | module.exports = solution 30 | 31 | /* 32 | 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). 33 | 34 | For example, array A such that: 35 | 36 | A[0] = 4 37 | A[1] = 2 38 | A[2] = 2 39 | A[3] = 5 40 | A[4] = 1 41 | A[5] = 5 42 | A[6] = 8 43 | contains the following example slices: 44 | 45 | slice (1, 2), whose average is (2 + 2) / 2 = 2; 46 | slice (3, 4), whose average is (5 + 1) / 2 = 3; 47 | slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5. 48 | The goal is to find the starting position of a slice whose average is minimal. 49 | 50 | Write a function: 51 | 52 | int solution(int A[], int N); 53 | 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. 54 | 55 | For example, given array A such that: 56 | 57 | A[0] = 4 58 | A[1] = 2 59 | A[2] = 2 60 | A[3] = 5 61 | A[4] = 1 62 | A[5] = 5 63 | A[6] = 8 64 | the function should return 1, as explained above. 65 | 66 | Assume that: 67 | 68 | N is an integer within the range [2..100,000]; 69 | each element of array A is an integer within the range [−10,000..10,000]. 70 | Complexity: 71 | 72 | expected worst-case time complexity is O(N); 73 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 74 | Elements of input arrays can be modified. 75 | */ -------------------------------------------------------------------------------- /codility/08_leader/dominator-leader-more-half.js: -------------------------------------------------------------------------------- 1 | // 91% 2 | function solution(A) { 3 | var len = A.length 4 | if (len === 1) return 0 5 | 6 | for (var i = 0; i < len; i++) { 7 | var count = 1 8 | 9 | for (var j = i+1; j < len; j++) { 10 | if (A[i] === A[j]) { 11 | count++ 12 | if (count / len > 0.5) return i 13 | } 14 | } 15 | } 16 | 17 | return -1 18 | } 19 | 20 | // 100% 21 | function solution(A) { 22 | var len = A.length 23 | if (len === 0) return -1 24 | 25 | var candidate 26 | var candidateIndex 27 | var candidateDiff 28 | 29 | for (var i = 0; i < len; i++) { 30 | if (!candidateDiff) { 31 | candidate = A[i] 32 | candidateIndex = i 33 | candidateDiff = 1 34 | } else { 35 | if (A[i] === candidate) { 36 | candidateDiff++ 37 | } else { 38 | candidateDiff-- 39 | } 40 | } 41 | } 42 | 43 | var candidateCount = 0 44 | for (var i = 0; i < len; i++) { 45 | if (A[i] === candidate) candidateCount++ 46 | } 47 | 48 | return candidateCount / len > 0.5 ? candidateIndex : -1 49 | } 50 | 51 | module.exports = solution 52 | 53 | /* 54 | 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. 55 | 56 | For example, consider array A such that 57 | 58 | A[0] = 3 A[1] = 4 A[2] = 3 59 | A[3] = 2 A[4] = 3 A[5] = -1 60 | A[6] = 3 A[7] = 3 61 | 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. 62 | 63 | Write a function 64 | 65 | int solution(int A[], int N); 66 | 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. 67 | 68 | Assume that: 69 | 70 | N is an integer within the range [0..100,000]; 71 | each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]. 72 | For example, given array A such that 73 | 74 | A[0] = 3 A[1] = 4 A[2] = 3 75 | A[3] = 2 A[4] = 3 A[5] = -1 76 | A[6] = 3 A[7] = 3 77 | the function may return 0, 2, 4, 6 or 7, as explained above. 78 | 79 | Complexity: 80 | 81 | expected worst-case time complexity is O(N); 82 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments). 83 | Elements of input arrays can be modified. 84 | */ -------------------------------------------------------------------------------- /codility/04_countingElements/frogRiverOne-jump-earliest.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(X, A) { 3 | var len = A.length 4 | var neededSum = 0 5 | var sum = 0 6 | var fallen = {} 7 | 8 | for (var i = 1; i <= X; i++) neededSum += i 9 | 10 | for (var i = 0; i < len; i++) { 11 | 12 | if (!fallen[A[i]]) { 13 | fallen[A[i]] = true 14 | sum += A[i] 15 | if (sum === neededSum) return i 16 | } 17 | } 18 | 19 | return -1 20 | } 21 | 22 | module.exports = solution 23 | 24 | /* 25 | A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Leaves fall from a tree onto the surface of the river. 26 | 27 | You are given a zero-indexed array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in seconds. 28 | 29 | The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X (that is, we want to find the earliest moment when all the positions from 1 to X are covered by leaves). You may assume that the speed of the current in the river is negligibly small, i.e. the leaves do not change their positions once they fall in the river. 30 | 31 | For example, you are given integer X = 5 and array A such that: 32 | 33 | A[0] = 1 34 | A[1] = 3 35 | A[2] = 1 36 | A[3] = 4 37 | A[4] = 2 38 | A[5] = 3 39 | A[6] = 5 40 | A[7] = 4 41 | In second 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river. 42 | 43 | Write a function: 44 | 45 | int solution(int X, int A[], int N); 46 | that, given a non-empty zero-indexed array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river. 47 | 48 | If the frog is never able to jump to the other side of the river, the function should return −1. 49 | 50 | For example, given X = 5 and array A such that: 51 | 52 | A[0] = 1 53 | A[1] = 3 54 | A[2] = 1 55 | A[3] = 4 56 | A[4] = 2 57 | A[5] = 3 58 | A[6] = 5 59 | A[7] = 4 60 | the function should return 6, as explained above. 61 | 62 | Assume that: 63 | 64 | N and X are integers within the range [1..100,000]; 65 | each element of array A is an integer within the range [1..X]. 66 | Complexity: 67 | 68 | expected worst-case time complexity is O(N); 69 | expected worst-case space complexity is O(X), beyond input storage (not counting the storage required for input arguments). 70 | Elements of input arrays can be modified. 71 | */ -------------------------------------------------------------------------------- /codility/08_leader/equiLeader-more-half-same.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | var candidates = {} 5 | var max = 0 6 | var candidate 7 | 8 | for (var i = 0; i < len; i++) { 9 | candidates[A[i]] = candidates[A[i]] ? candidates[A[i]]+1 : 1 10 | 11 | if (candidates[A[i]] > max) { 12 | max = candidates[A[i]] 13 | candidate = A[i] 14 | } 15 | } 16 | 17 | var sums = {} 18 | var countLeft = 0 19 | var countRight = 0 20 | 21 | for (var i = 0; i < len-1; i++) { 22 | if (A[i] === candidate) countLeft++ 23 | 24 | sums[i] = sums[i] || { prev: 0, next: 0} 25 | sums[i].prev = countLeft 26 | 27 | var j = len-i-2 28 | if (A[j+1] === candidate) countRight++ 29 | 30 | sums[j] = sums[j] || { prev: 0, next: 0} 31 | sums[j].next = countRight 32 | } 33 | 34 | var eqLeaderCount = 0 35 | 36 | for (var k in sums) { 37 | k = +k 38 | if (sums[k].prev / (k+1) > 0.5 && sums[k].next / (len-k-1) > 0.5) { 39 | eqLeaderCount++ 40 | } 41 | } 42 | 43 | return eqLeaderCount 44 | } 45 | 46 | module.exports = solution 47 | 48 | /* 49 | A non-empty zero-indexed array A consisting of N integers is given. 50 | 51 | The leader of this array is the value that occurs in more than half of the elements of A. 52 | 53 | 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. 54 | 55 | For example, given array A such that: 56 | 57 | A[0] = 4 58 | A[1] = 3 59 | A[2] = 4 60 | A[3] = 4 61 | A[4] = 4 62 | A[5] = 2 63 | we can find two equi leaders: 64 | 65 | 0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4. 66 | 2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4. 67 | The goal is to count the number of equi leaders. 68 | 69 | Write a function: 70 | 71 | int solution(int A[], int N); 72 | that, given a non-empty zero-indexed array A consisting of N integers, returns the number of equi leaders. 73 | 74 | For example, given: 75 | 76 | A[0] = 4 77 | A[1] = 3 78 | A[2] = 4 79 | A[3] = 4 80 | A[4] = 4 81 | A[5] = 2 82 | the function should return 2, as explained above. 83 | 84 | Assume that: 85 | 86 | N is an integer within the range [1..100,000]; 87 | each element of array A is an integer within the range [−1,000,000,000..1,000,000,000]. 88 | Complexity: 89 | 90 | expected worst-case time complexity is O(N); 91 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 92 | Elements of input arrays can be modified. 93 | */ 94 | -------------------------------------------------------------------------------- /codility/13_fibonacciNumbers/ladder-large-modulo-steps.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A, B) { 3 | var i = 1 4 | var fib = [1, 1] 5 | var maxA = Math.max.apply(null, A) 6 | var maxB = Math.max.apply(null, B) 7 | 8 | while (i++ <= maxA) { 9 | fib.push((fib[i-1] + fib[i-2]) % Math.pow(2, maxB)) 10 | } 11 | 12 | var result = [] 13 | for (i = 0; i < A.length; i++) { 14 | result.push(fib[A[i]] % Math.pow(2, B[i])) 15 | } 16 | 17 | return result 18 | } 19 | 20 | module.exports = solution 21 | 22 | /* 23 | 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: 24 | 25 | with your first step you can stand on rung 1 or 2, 26 | if you are on rung K, you can move to rungs K + 1 or K + 2, 27 | finally you have to stand on rung N. 28 | Your task is to count the number of different ways of climbing to the top of the ladder. 29 | 30 | For example, given N = 4, you have five different ways of climbing, ascending by: 31 | 32 | 1, 1, 1 and 1 rung, 33 | 1, 1 and 2 rungs, 34 | 1, 2 and 1 rung, 35 | 2, 1 and 1 rungs, and 36 | 2 and 2 rungs. 37 | Given N = 5, you have eight different ways of climbing, ascending by: 38 | 39 | 1, 1, 1, 1 and 1 rung, 40 | 1, 1, 1 and 2 rungs, 41 | 1, 1, 2 and 1 rung, 42 | 1, 2, 1 and 1 rung, 43 | 1, 2 and 2 rungs, 44 | 2, 1, 1 and 1 rungs, 45 | 2, 1 and 2 rungs, and 46 | 2, 2 and 1 rung. 47 | The number of different ways can be very large, so it is sufficient to return the result modulo 2P, for a given integer P. 48 | 49 | Assume that the following declarations are given: 50 | 51 | struct Results { 52 | int * C; 53 | int L; 54 | }; 55 | Write a function: 56 | 57 | struct Results solution(int A[], int B[], int L); 58 | 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]. 59 | 60 | For example, given L = 5 and: 61 | 62 | A[0] = 4 B[0] = 3 63 | A[1] = 4 B[1] = 2 64 | A[2] = 5 B[2] = 4 65 | A[3] = 5 B[3] = 3 66 | A[4] = 1 B[4] = 1 67 | the function should return the sequence [5, 1, 8, 0, 1], as explained above. 68 | 69 | Assume that: 70 | 71 | L is an integer within the range [1..30,000]; 72 | each element of array A is an integer within the range [1..L]; 73 | each element of array B is an integer within the range [1..30]. 74 | Complexity: 75 | 76 | expected worst-case time complexity is O(L); 77 | expected worst-case space complexity is O(L), beyond input storage (not counting the storage required for input arguments). 78 | Elements of input arrays can be modified. 79 | */ -------------------------------------------------------------------------------- /codility/06_sorting/numberOfDiscIntersections-radius.js: -------------------------------------------------------------------------------- 1 | // 81% 2 | function solution(A) { 3 | var len = A.length 4 | var pairsCount = 0 5 | 6 | for (var i = 0; i < len; i++) { 7 | for (var j = i+1; j < len; j++) { 8 | if (i + A[i] >= j - A[j]) { 9 | pairsCount++ 10 | } 11 | } 12 | if (pairsCount > 10000000) return -1 13 | } 14 | 15 | return pairsCount 16 | } 17 | 18 | // 100% - NEED TO REWRITE 19 | function solution(A) { 20 | var len = A.length 21 | var pairs = 0 22 | var starts = [] 23 | var ends = [] 24 | 25 | for (var i = 0; i < len; i++) { 26 | starts[i] = 0 27 | ends[i] = 0 28 | } 29 | 30 | for (var i = 0; i < len; i++) { 31 | starts[Math.max(0, i - A[i])]++ 32 | if (i < len - A[i]) ends[i + A[i]]++ 33 | } 34 | 35 | var active = 0 36 | for (var i = 0; i < len; i++) { 37 | 38 | if (starts[i] > 0) { 39 | pairs += active * starts[i] 40 | pairs += starts[i] * (starts[i] - 1) / 2 41 | active += starts[i] 42 | if (pairs > 10000000) return -1 43 | } 44 | 45 | active -= ends[i] 46 | } 47 | 48 | return pairs 49 | } 50 | 51 | 52 | module.exports = solution 53 | 54 | /* 55 | We draw N discs on a plane. The discs are numbered from 0 to N − 1. A zero-indexed array A of N non-negative integers, specifying the radiuses of the discs, is given. The J-th disc is drawn with its center at (J, 0) and radius A[J]. 56 | 57 | We say that the J-th disc and K-th disc intersect if J ≠ K and the J-th and K-th discs have at least one common point (assuming that the discs contain their borders). 58 | 59 | The figure below shows discs drawn for N = 6 and A as follows: 60 | 61 | A[0] = 1 62 | A[1] = 5 63 | A[2] = 2 64 | A[3] = 1 65 | A[4] = 4 66 | A[5] = 0 67 | 68 | 69 | There are eleven (unordered) pairs of discs that intersect, namely: 70 | 71 | discs 1 and 4 intersect, and both intersect with all the other discs; 72 | disc 2 also intersects with discs 0 and 3. 73 | Write a function: 74 | 75 | int solution(int A[], int N); 76 | that, given an array A describing N discs as explained above, returns the number of (unordered) pairs of intersecting discs. The function should return −1 if the number of intersecting pairs exceeds 10,000,000. 77 | 78 | Given array A shown above, the function should return 11, as explained above. 79 | 80 | Assume that: 81 | 82 | N is an integer within the range [0..100,000]; 83 | each element of array A is an integer within the range [0..2,147,483,647]. 84 | Complexity: 85 | 86 | expected worst-case time complexity is O(N*log(N)); 87 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 88 | Elements of input arrays can be modified. 89 | */ -------------------------------------------------------------------------------- /codility/11_sieveOfEratosthenes/countNonDivisible.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function getDivisors(N) { 3 | var divisors = [] 4 | var limit = Math.floor(Math.sqrt(N)) 5 | 6 | for (var i = 1; i <= limit; i++) { 7 | if (N % i === 0) { 8 | divisors.push(i) 9 | if (N / i !== i) divisors.push(N / i) 10 | } 11 | } 12 | 13 | return divisors 14 | } 15 | 16 | function solution(A) { 17 | var len = A.length 18 | var result = [] 19 | var counts = {} 20 | for (var i = 0; i < len; i++) counts[A[i]] = 0 21 | for (var i = 0; i < len; i++) counts[A[i]]++ 22 | 23 | for (var i = 0; i < len; i++) { 24 | var count = len 25 | var divisors = getDivisors(A[i]) 26 | var dlen = divisors.length 27 | 28 | for (var d = 0; d < dlen; d++) { 29 | if (counts[divisors[d]]) count -= counts[divisors[d]] 30 | } 31 | 32 | result.push(count) 33 | } 34 | 35 | return result 36 | } 37 | 38 | module.exports = solution 39 | 40 | /* 41 | You are given a non-empty zero-indexed array A consisting of N integers. 42 | 43 | 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. 44 | 45 | For example, consider integer N = 5 and array A such that: 46 | 47 | A[0] = 3 48 | A[1] = 1 49 | A[2] = 2 50 | A[3] = 3 51 | A[4] = 6 52 | For the following elements: 53 | 54 | A[0] = 3, the non-divisors are: 2, 6, 55 | A[1] = 1, the non-divisors are: 3, 2, 3, 6, 56 | A[2] = 2, the non-divisors are: 3, 3, 6, 57 | A[3] = 3, the non-divisors are: 2, 6, 58 | A[4] = 6, there aren't any non-divisors. 59 | Assume that the following declarations are given: 60 | 61 | struct Results { 62 | int * C; 63 | int L; 64 | }; 65 | Write a function: 66 | 67 | struct Results solution(int A[], int N); 68 | that, given a non-empty zero-indexed array A consisting of N integers, returns a sequence of integers representing the amount of non-divisors. 69 | 70 | The sequence should be returned as: 71 | 72 | a structure Results (in C), or 73 | a vector of integers (in C++), or 74 | a record Results (in Pascal), or 75 | an array of integers (in any other programming language). 76 | For example, given: 77 | 78 | A[0] = 3 79 | A[1] = 1 80 | A[2] = 2 81 | A[3] = 3 82 | A[4] = 6 83 | the function should return [2, 4, 3, 2, 0], as explained above. 84 | 85 | Assume that: 86 | 87 | N is an integer within the range [1..50,000]; 88 | each element of array A is an integer within the range [1..2 * N]. 89 | Complexity: 90 | 91 | expected worst-case time complexity is O(N*log(N)); 92 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 93 | Elements of input arrays can be modified. 94 | */ -------------------------------------------------------------------------------- /codility/04_countingElements/maxCounters.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(N, A) { 3 | var len = A.length 4 | var max = 0, min = 0 5 | var counters = [] 6 | for (var c = 0; c < N; c++) counters.push(0) 7 | 8 | for (var i = 0; i < len; i++) { 9 | 10 | if (A[i] <= N) { 11 | var target = A[i]-1 12 | counters[target] = Math.max(counters[target], min) 13 | max = Math.max(max, ++counters[target]) 14 | 15 | } else { 16 | min = max 17 | } 18 | } 19 | 20 | for (var j = 0; j < N; j++) { 21 | counters[j] = Math.max(counters[j], min) 22 | } 23 | 24 | return counters 25 | } 26 | 27 | module.exports = solution 28 | 29 | /* 30 | You are given N counters, initially set to 0, and you have two possible operations on them: 31 | 32 | increase(X) − counter X is increased by 1, 33 | max counter − all counters are set to the maximum value of any counter. 34 | A non-empty zero-indexed array A of M integers is given. This array represents consecutive operations: 35 | 36 | if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X), 37 | if A[K] = N + 1 then operation K is max counter. 38 | For example, given integer N = 5 and array A such that: 39 | 40 | A[0] = 3 41 | A[1] = 4 42 | A[2] = 4 43 | A[3] = 6 44 | A[4] = 1 45 | A[5] = 4 46 | A[6] = 4 47 | the values of the counters after each consecutive operation will be: 48 | 49 | (0, 0, 1, 0, 0) 50 | (0, 0, 1, 1, 0) 51 | (0, 0, 1, 2, 0) 52 | (2, 2, 2, 2, 2) 53 | (3, 2, 2, 2, 2) 54 | (3, 2, 2, 3, 2) 55 | (3, 2, 2, 4, 2) 56 | The goal is to calculate the value of every counter after all operations. 57 | 58 | Assume that the following declarations are given: 59 | 60 | struct Results { 61 | int * C; 62 | int L; 63 | }; 64 | Write a function: 65 | 66 | struct Results solution(int N, int A[], int M); 67 | 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. 68 | 69 | The sequence should be returned as: 70 | 71 | a structure Results (in C), or 72 | a vector of integers (in C++), or 73 | a record Results (in Pascal), or 74 | an array of integers (in any other programming language). 75 | For example, given: 76 | 77 | A[0] = 3 78 | A[1] = 4 79 | A[2] = 4 80 | A[3] = 6 81 | A[4] = 1 82 | A[5] = 4 83 | A[6] = 4 84 | the function should return [3, 2, 2, 4, 2], as explained above. 85 | 86 | Assume that: 87 | 88 | N and M are integers within the range [1..100,000]; 89 | each element of array A is an integer within the range [1..N + 1]. 90 | Complexity: 91 | 92 | expected worst-case time complexity is O(N+M); 93 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 94 | Elements of input arrays can be modified. 95 | */ -------------------------------------------------------------------------------- /codility/11_sieveOfEratosthenes/countSemiPrimes.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(N, P, Q) { 3 | var i = 0 4 | var primes = [] 5 | var semiPrimes = [] 6 | 7 | for (i = 2; i < N; i++) { 8 | primes[i] = true 9 | semiPrimes[i] = false 10 | } 11 | 12 | for (i = 2; i <= parseInt(Math.sqrt(N)); i++) { 13 | for (var j = i; j * i <= N; j++) { 14 | primes[j*i] = false 15 | semiPrimes[j*i] = primes[i] && primes[j] ? true : false 16 | } 17 | } 18 | 19 | var sums = [0, 0] 20 | var count = 0 21 | for (i = 2; i <= N; i++) { 22 | sums.push(semiPrimes[i] ? ++count : count) 23 | } 24 | 25 | var result = [] 26 | for (i = 0; i < Q.length; i++) { 27 | result.push(sums[Q[i]] - sums[P[i]-1]) 28 | } 29 | 30 | return result 31 | } 32 | 33 | module.exports = solution 34 | 35 | /* 36 | 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. 37 | 38 | 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. 39 | 40 | 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. 41 | 42 | Query K requires you to find the number of semiprimes within the range (P[K], Q[K]), where 1 ≤ P[K] ≤ Q[K] ≤ N. 43 | 44 | For example, consider an integer N = 26 and arrays P, Q such that: 45 | 46 | P[0] = 1 Q[0] = 26 47 | P[1] = 4 Q[1] = 10 48 | P[2] = 16 Q[2] = 20 49 | The number of semiprimes within each of these ranges is as follows: 50 | 51 | (1, 26) is 10, 52 | (4, 10) is 4, 53 | (16, 20) is 0. 54 | Assume that the following declarations are given: 55 | 56 | struct Results { 57 | int * A; 58 | int M; 59 | }; 60 | Write a function: 61 | 62 | struct Results solution(int N, int P[], int Q[], int M); 63 | 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. 64 | 65 | For example, given an integer N = 26 and arrays P, Q such that: 66 | 67 | P[0] = 1 Q[0] = 26 68 | P[1] = 4 Q[1] = 10 69 | P[2] = 16 Q[2] = 20 70 | the function should return the values [10, 4, 0], as explained above. 71 | 72 | Assume that: 73 | 74 | N is an integer within the range [1..50,000]; 75 | M is an integer within the range [1..30,000]; 76 | each element of arrays P, Q is an integer within the range [1..N]; 77 | P[i] ≤ Q[i]. 78 | Complexity: 79 | 80 | expected worst-case time complexity is O(N*log(log(N))+M); 81 | expected worst-case space complexity is O(N+M), beyond input storage (not counting the storage required for input arguments). 82 | Elements of input arrays can be modified. 83 | */ -------------------------------------------------------------------------------- /codility/15_caterpillarMethod/minAbsSumOfTwo-pairs.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | var pos = [] 5 | var neg = [] 6 | var min = Infinity 7 | 8 | for (var i = 0; i < len; i++) { 9 | A[i] >= 0 ? pos.push(A[i]) : neg.push(A[i]) 10 | } 11 | 12 | pos.sort((a, b) => a - b) 13 | neg.sort((a, b) => b - a) 14 | 15 | if (pos[0] === 0) return 0 16 | if (pos.length) min = pos[0]*2 17 | if (neg.length) min = Math.min(min, Math.abs(neg[0]*2)) 18 | if (!neg.length || !pos.length) return min 19 | 20 | for (var i = 0; i < neg.length; i++) { 21 | var start = 0 22 | var end = pos.length-1 23 | var currNeg = neg[i] 24 | 25 | while (start <= end) { 26 | var mid = Math.floor((start+end)/2) 27 | var currPos = pos[mid] 28 | min = Math.min(min, Math.abs(currNeg+currPos)) 29 | 30 | if (end === start) break; 31 | if (Math.abs(currNeg) <= currPos) { 32 | end = mid 33 | } else { 34 | start = mid + 1 35 | } 36 | } 37 | 38 | if (!min) return 0 39 | } 40 | 41 | return min 42 | } 43 | 44 | module.exports = solution 45 | 46 | /* 47 | Let A be a non-empty zero-indexed array consisting of N integers. 48 | 49 | 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. 50 | 51 | For example, the following array A: 52 | 53 | A[0] = 1 54 | A[1] = 4 55 | A[2] = -3 56 | has pairs of indices (0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2). 57 | The abs sum of two for the pair (0, 0) is A[0] + A[0] = |1 + 1| = 2. 58 | The abs sum of two for the pair (0, 1) is A[0] + A[1] = |1 + 4| = 5. 59 | The abs sum of two for the pair (0, 2) is A[0] + A[2] = |1 + (−3)| = 2. 60 | The abs sum of two for the pair (1, 1) is A[1] + A[1] = |4 + 4| = 8. 61 | The abs sum of two for the pair (1, 2) is A[1] + A[2] = |4 + (−3)| = 1. 62 | The abs sum of two for the pair (2, 2) is A[2] + A[2] = |(−3) + (−3)| = 6. 63 | Write a function: 64 | 65 | int solution(int A[], int N); 66 | 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. 67 | 68 | For example, given the following array A: 69 | 70 | A[0] = 1 71 | A[1] = 4 72 | A[2] = -3 73 | the function should return 1, as explained above. 74 | 75 | Given array A: 76 | 77 | A[0] = -8 78 | A[1] = 4 79 | A[2] = 5 80 | A[3] =-10 81 | A[4] = 3 82 | the function should return |(−8) + 5| = 3. 83 | 84 | Assume that: 85 | 86 | N is an integer within the range [1..100,000]; 87 | each element of array A is an integer within the range [−1,000,000,000..1,000,000,000]. 88 | Complexity: 89 | 90 | expected worst-case time complexity is O(N*log(N)); 91 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 92 | Elements of input arrays can be modified. 93 | */ 94 | -------------------------------------------------------------------------------- /codility/17_dynamicProgramming/numberSolitaire-dynamic-dice-six-marked.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | var sums = [A[0]] 5 | for (var s = 1; s < len; s++) sums[s] = -Infinity 6 | 7 | for (var i = 1; i < len; i++) { 8 | for (var j = Math.max(0, i-6); j < i; j++) { 9 | sums[i] = Math.max(sums[i], sums[j] + A[i]) 10 | } 11 | } 12 | 13 | return sums[sums.length-1] 14 | } 15 | 16 | module.exports = solution 17 | 18 | /* 19 | A game for one player is played on a board consisting of N consecutive squares, numbered from 0 to N − 1. There is a number written on each square. A non-empty zero-indexed array A of N integers contains the numbers written on the squares. Moreover, some squares can be marked during the game. 20 | 21 | At the beginning of the game, there is a pebble on square number 0 and this is the only square on the board which is marked. The goal of the game is to move the pebble to square number N − 1. 22 | 23 | During each turn we throw a six-sided die, with numbers from 1 to 6 on its faces, and consider the number K, which shows on the upper face after the die comes to rest. Then we move the pebble standing on square number I to square number I + K, providing that square number I + K exists. If square number I + K does not exist, we throw the die again until we obtain a valid move. Finally, we mark square number I + K. 24 | 25 | After the game finishes (when the pebble is standing on square number N − 1), we calculate the result. The result of the game is the sum of the numbers written on all marked squares. 26 | 27 | For example, given the following array: 28 | 29 | A[0] = 1 30 | A[1] = -2 31 | A[2] = 0 32 | A[3] = 9 33 | A[4] = -1 34 | A[5] = -2 35 | one possible game could be as follows: 36 | 37 | the pebble is on square number 0, which is marked; 38 | we throw 3; the pebble moves from square number 0 to square number 3; we mark square number 3; 39 | we throw 5; the pebble does not move, since there is no square number 8 on the board; 40 | we throw 2; the pebble moves to square number 5; we mark this square and the game ends. 41 | The marked squares are 0, 3 and 5, so the result of the game is 1 + 9 + (−2) = 8. This is the maximal possible result that can be achieved on this board. 42 | 43 | Write a function: 44 | 45 | int solution(int A[], int N); 46 | that, given a non-empty zero-indexed array A of N integers, returns the maximal result that can be achieved on the board represented by array A. 47 | 48 | For example, given the array 49 | 50 | A[0] = 1 51 | A[1] = -2 52 | A[2] = 0 53 | A[3] = 9 54 | A[4] = -1 55 | A[5] = -2 56 | the function should return 8, as explained above. 57 | 58 | Assume that: 59 | 60 | N is an integer within the range [2..100,000]; 61 | each element of array A is an integer within the range [−10,000..10,000]. 62 | Complexity: 63 | 64 | expected worst-case time complexity is O(N); 65 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 66 | Elements of input arrays can be modified. 67 | */ -------------------------------------------------------------------------------- /codility/09_maxSlice/maxDoubleSliceSum.js: -------------------------------------------------------------------------------- 1 | // 100% - NEED TO REWRITE 2 | function solution(A) { 3 | var len = A.length 4 | var maxEnds = [], maxEnd = 0 5 | var maxBegins = [], maxBegin = 0 6 | 7 | for (var i = 0; i < len; i++) { 8 | maxEnds[i] = 0 9 | maxBegins[i] = 0 10 | } 11 | 12 | for (var i = 1; i < len-1; i++) { 13 | maxEnd = Math.max(0, A[i] + maxEnd) 14 | maxEnds[i] = maxEnd 15 | } 16 | 17 | for (var i = len-2; i >= 0; i--) { 18 | maxBegin = Math.max(0, A[i] + maxBegin) 19 | maxBegins[i] = maxBegin 20 | } 21 | 22 | var maxDoubleSlice = 0 23 | for (var i = 0; i < len-2; i++) { 24 | maxDoubleSlice = Math.max(maxDoubleSlice, maxEnds[i] + maxBegins[i+2]) 25 | } 26 | 27 | return maxDoubleSlice 28 | } 29 | 30 | // 100% - NEED TO REWRITE 31 | function solution(A) { 32 | var len = A.length 33 | var leftSums = [], rightSums = [] 34 | 35 | for (var i = 0; i < len; i++) { 36 | leftSums[i] = 0 37 | rightSums[i] = 0 38 | } 39 | 40 | for (var i = 1; i < len-1; i++) { 41 | leftSums[i] = Math.max(leftSums[i-1] + A[i], 0) 42 | } 43 | 44 | for (var i = len-2; i > 0; i--) { 45 | rightSums[i] = Math.max(rightSums[i+1] + A[i], 0) 46 | } 47 | 48 | var max = 0 49 | for (var i = 1; i < len-1; i++) { 50 | max = Math.max(max, leftSums[i-1] + rightSums[i+1]) 51 | } 52 | 53 | return max 54 | } 55 | 56 | module.exports = solution 57 | 58 | /* 59 | A non-empty zero-indexed array A consisting of N integers is given. 60 | 61 | A triplet (X, Y, Z), such that 0 ≤ X < Y < Z < N, is called a double slice. 62 | 63 | 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]. 64 | 65 | For example, array A such that: 66 | 67 | A[0] = 3 68 | A[1] = 2 69 | A[2] = 6 70 | A[3] = -1 71 | A[4] = 4 72 | A[5] = 5 73 | A[6] = -1 74 | A[7] = 2 75 | contains the following example double slices: 76 | 77 | double slice (0, 3, 6), sum is 2 + 6 + 4 + 5 = 17, 78 | double slice (0, 3, 7), sum is 2 + 6 + 4 + 5 − 1 = 16, 79 | double slice (3, 4, 5), sum is 0. 80 | The goal is to find the maximal sum of any double slice. 81 | 82 | Write a function: 83 | 84 | int solution(int A[], int N); 85 | that, given a non-empty zero-indexed array A consisting of N integers, returns the maximal sum of any double slice. 86 | 87 | For example, given: 88 | 89 | A[0] = 3 90 | A[1] = 2 91 | A[2] = 6 92 | A[3] = -1 93 | A[4] = 4 94 | A[5] = 5 95 | A[6] = -1 96 | A[7] = 2 97 | the function should return 17, because no double slice of array A has a sum of greater than 17. 98 | 99 | Assume that: 100 | 101 | N is an integer within the range [3..100,000]; 102 | each element of array A is an integer within the range [−10,000..10,000]. 103 | Complexity: 104 | 105 | expected worst-case time complexity is O(N); 106 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 107 | Elements of input arrays can be modified. 108 | */ 109 | -------------------------------------------------------------------------------- /codility/10_primeAndCompositeNumbers/flags-peaks-higher-neighbors.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | var peaks = [] 5 | 6 | for (var i = 0; i < len; i++) { 7 | if (A[i] > A[i-1] && A[i] > A[i+1]) { 8 | peaks.push(i) 9 | } 10 | } 11 | 12 | var pLen = peaks.length 13 | if (!pLen) return 0 14 | var limit = Math.floor(Math.sqrt(len)) + 1 15 | 16 | for (var k = limit; k >= 1; k--) { 17 | var flagsCount = 1 18 | var lastFlag = 0 19 | 20 | for (var p = 1; p < pLen; p++) { 21 | 22 | if (peaks[p] - peaks[lastFlag] >= k) { 23 | lastFlag = p 24 | flagsCount++ 25 | } 26 | } 27 | 28 | if (flagsCount >= k) return k 29 | } 30 | 31 | return 0 32 | } 33 | 34 | module.exports = solution 35 | 36 | /* 37 | A non-empty zero-indexed array A consisting of N integers is given. 38 | 39 | 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]. 40 | 41 | For example, the following array A: 42 | 43 | A[0] = 1 44 | A[1] = 5 45 | A[2] = 3 46 | A[3] = 4 47 | A[4] = 3 48 | A[5] = 4 49 | A[6] = 1 50 | A[7] = 2 51 | A[8] = 3 52 | A[9] = 4 53 | A[10] = 6 54 | A[11] = 2 55 | has exactly four peaks: elements 1, 3, 5 and 10. 56 | 57 | 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. 58 | 59 | 60 | 61 | 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|. 62 | 63 | For example, given the mountain range represented by array A, above, with N = 12, if you take: 64 | 65 | two flags, you can set them on peaks 1 and 5; 66 | three flags, you can set them on peaks 1, 5 and 10; 67 | four flags, you can set only three flags, on peaks 1, 5 and 10. 68 | You can therefore set a maximum of three flags in this case. 69 | 70 | Write a function: 71 | 72 | int solution(int A[], int N); 73 | 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. 74 | 75 | For example, the following array A: 76 | 77 | A[0] = 1 78 | A[1] = 5 79 | A[2] = 3 80 | A[3] = 4 81 | A[4] = 3 82 | A[5] = 4 83 | A[6] = 1 84 | A[7] = 2 85 | A[8] = 3 86 | A[9] = 4 87 | A[10] = 6 88 | A[11] = 2 89 | the function should return 3, as explained above. 90 | 91 | Assume that: 92 | 93 | N is an integer within the range [1..400,000]; 94 | each element of array A is an integer within the range [0..1,000,000,000]. 95 | Complexity: 96 | 97 | expected worst-case time complexity is O(N); 98 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 99 | Elements of input arrays can be modified. 100 | */ -------------------------------------------------------------------------------- /codility/14_binarySearchAlgorithm/minMaxDivision-divide-blocks-minimize-sum-binary-search.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(K, M, A) { 3 | var len = A.length 4 | var start = 0 5 | var end = 0 6 | 7 | for (var i = 0; i < len; i++) { 8 | end += A[i] 9 | start = Math.max(start, A[i]) 10 | } 11 | 12 | if (!start) return 0 13 | if (K === 1) return end 14 | var mid 15 | var minSum = end 16 | 17 | while (start <= end) { 18 | var oldMid = mid 19 | mid = Math.floor((end+start)/2) 20 | if (oldMid === mid) break; 21 | 22 | var count = 0 23 | var blockSum = 0 24 | var maxBlockSum = 0 25 | 26 | for (var i = 0; i < len; i++) { 27 | if (blockSum + A[i] > mid) { 28 | count++ 29 | maxBlockSum = Math.max(maxBlockSum, blockSum) 30 | blockSum = 0 31 | } 32 | 33 | blockSum += A[i] 34 | 35 | if (i === len-1) { 36 | count++ 37 | maxBlockSum = Math.max(maxBlockSum, blockSum) 38 | } 39 | } 40 | 41 | if (count <= K) { 42 | minSum = Math.min(minSum, maxBlockSum) 43 | end = mid 44 | } else { 45 | start = mid + 1 46 | } 47 | } 48 | 49 | return minSum 50 | } 51 | 52 | module.exports = solution 53 | 54 | /* 55 | 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. 56 | 57 | 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. 58 | 59 | The sum of the block from X to Y equals A[X] + A[X + 1] + ... + A[Y]. The sum of empty block equals 0. 60 | 61 | The large sum is the maximal sum of any block. 62 | 63 | For example, you are given integers K = 3, M = 5 and array A such that: 64 | 65 | A[0] = 2 66 | A[1] = 1 67 | A[2] = 5 68 | A[3] = 1 69 | A[4] = 2 70 | A[5] = 2 71 | A[6] = 2 72 | The array can be divided, for example, into the following blocks: 73 | 74 | [2, 1, 5, 1, 2, 2, 2], [], [] with a large sum of 15; 75 | [2], [1, 5, 1, 2], [2, 2] with a large sum of 9; 76 | [2, 1, 5], [], [1, 2, 2, 2] with a large sum of 8; 77 | [2, 1], [5, 1], [2, 2, 2] with a large sum of 6. 78 | The goal is to minimize the large sum. In the above example, 6 is the minimal large sum. 79 | 80 | Write a function: 81 | 82 | int solution(int K, int M, int A[], int N); 83 | that, given integers K, M and a non-empty zero-indexed array A consisting of N integers, returns the minimal large sum. 84 | 85 | For example, given K = 3, M = 5 and array A such that: 86 | 87 | A[0] = 2 88 | A[1] = 1 89 | A[2] = 5 90 | A[3] = 1 91 | A[4] = 2 92 | A[5] = 2 93 | A[6] = 2 94 | the function should return 6, as explained above. 95 | 96 | Assume that: 97 | 98 | N and K are integers within the range [1..100,000]; 99 | M is an integer within the range [0..10,000]; 100 | each element of array A is an integer within the range [0..M]. 101 | Complexity: 102 | 103 | expected worst-case time complexity is O(N*log(N+M)); 104 | expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments). 105 | Elements of input arrays can be modified. 106 | */ -------------------------------------------------------------------------------- /codility/14_binarySearchAlgorithm/nailingPlanks-minimal-number-used.js: -------------------------------------------------------------------------------- 1 | // 62% - NEEDS REWRITE 2 | function solution(A, B, C) { 3 | var planksLeft = A.length 4 | var nailsUsed = 0 5 | 6 | for (var i = 0; i < C.length; i++) { 7 | 8 | for (var k = 0; k < A.length; k++) { 9 | if (A[k] && A[k] <= C[i] && C[i] <= B[k]) { 10 | A[k] = null 11 | planksLeft-- 12 | } 13 | } 14 | 15 | nailsUsed++ 16 | if (!planksLeft) break; 17 | } 18 | 19 | return planksLeft ? -1 : nailsUsed 20 | } 21 | 22 | module.exports = solution 23 | 24 | /* 25 | 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. 26 | 27 | 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. 28 | 29 | 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]. 30 | 31 | 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]. 32 | 33 | For example, given arrays A, B such that: 34 | 35 | A[0] = 1 B[0] = 4 36 | A[1] = 4 B[1] = 5 37 | A[2] = 5 B[2] = 9 38 | A[3] = 8 B[3] = 10 39 | four planks are represented: [1, 4], [4, 5], [5, 9] and [8, 10]. 40 | 41 | Given array C such that: 42 | 43 | C[0] = 4 44 | C[1] = 6 45 | C[2] = 7 46 | C[3] = 10 47 | C[4] = 2 48 | if we use the following nails: 49 | 50 | 0, then planks [1, 4] and [4, 5] will both be nailed. 51 | 0, 1, then planks [1, 4], [4, 5] and [5, 9] will be nailed. 52 | 0, 1, 2, then planks [1, 4], [4, 5] and [5, 9] will be nailed. 53 | 0, 1, 2, 3, then all the planks will be nailed. 54 | Thus, four is the minimum number of nails that, used sequentially, allow all the planks to be nailed. 55 | 56 | Write a function: 57 | 58 | int solution(int A[], int B[], int N, int C[], int M); 59 | 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. 60 | 61 | If it is not possible to nail all the planks, the function should return −1. 62 | 63 | For example, given arrays A, B, C such that: 64 | 65 | A[0] = 1 B[0] = 4 66 | A[1] = 4 B[1] = 5 67 | A[2] = 5 B[2] = 9 68 | A[3] = 8 B[3] = 10 69 | 70 | C[0] = 4 71 | C[1] = 6 72 | C[2] = 7 73 | C[3] = 10 74 | C[4] = 2 75 | the function should return 4, as explained above. 76 | 77 | Assume that: 78 | 79 | N and M are integers within the range [1..30,000]; 80 | each element of arrays A, B, C is an integer within the range [1..2*M]; 81 | A[K] ≤ B[K]. 82 | Complexity: 83 | 84 | expected worst-case time complexity is O((N+M)*log(M)); 85 | expected worst-case space complexity is O(M), beyond input storage (not counting the storage required for input arguments). 86 | Elements of input arrays can be modified. 87 | */ -------------------------------------------------------------------------------- /codility/13_fibonacciNumbers/fibFrog-fibonacci-jump.js: -------------------------------------------------------------------------------- 1 | // 50% - NOT ACCURATE - NEEDS REWRITE 2 | function fibSequence(N) { 3 | var last = 0, curr = 1 4 | var sequence = {} 5 | 6 | while (curr <= N) { 7 | var temp = last 8 | last = curr 9 | curr += temp 10 | sequence[last] = true 11 | } 12 | 13 | return sequence 14 | } 15 | 16 | function solution(A) { 17 | A.unshift(1) 18 | A.push(1) 19 | var len = A.length 20 | var sequence = fibSequence(len-1) 21 | 22 | if (sequence[len-1]) return 1 23 | 24 | var jumps = 0 25 | var pos = 0 26 | var i = len-1 27 | 28 | while (i > pos) { 29 | if (A[i] && sequence[i-pos]) { 30 | pos = i 31 | i = len-1 32 | jumps++ 33 | if (pos === len-1) return jumps 34 | } else { 35 | if (--i === pos) { 36 | if (pos === 0) break; 37 | A[pos] = 0 38 | pos = 0 39 | i = len-1 40 | jumps = 0 41 | } 42 | } 43 | } 44 | 45 | return -1 46 | } 47 | 48 | module.exports = solution 49 | 50 | /* 51 | The Fibonacci sequence is defined using the following recursive formula: 52 | 53 | F(0) = 0 54 | F(1) = 1 55 | F(M) = F(M - 1) + F(M - 2) if M >= 2 56 | 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. 57 | 58 | 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: 59 | 60 | 0 represents a position without a leaf; 61 | 1 represents a position containing a leaf. 62 | 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. 63 | 64 | For example, consider array A such that: 65 | 66 | A[0] = 0 67 | A[1] = 0 68 | A[2] = 0 69 | A[3] = 1 70 | A[4] = 1 71 | A[5] = 0 72 | A[6] = 1 73 | A[7] = 0 74 | A[8] = 0 75 | A[9] = 0 76 | A[10] = 0 77 | The frog can make three jumps of length F(5) = 5, F(3) = 2 and F(5) = 5. 78 | 79 | Write a function: 80 | 81 | int solution(int A[], int N); 82 | 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. 83 | 84 | For example, given: 85 | 86 | A[0] = 0 87 | A[1] = 0 88 | A[2] = 0 89 | A[3] = 1 90 | A[4] = 1 91 | A[5] = 0 92 | A[6] = 1 93 | A[7] = 0 94 | A[8] = 0 95 | A[9] = 0 96 | A[10] = 0 97 | the function should return 3, as explained above. 98 | 99 | Assume that: 100 | 101 | N is an integer within the range [0..100,000]; 102 | each element of array A is an integer that can have one of the following values: 0, 1. 103 | Complexity: 104 | 105 | expected worst-case time complexity is O(N*log(N)); 106 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 107 | Elements of input arrays can be modified. 108 | */ 109 | -------------------------------------------------------------------------------- /codility/07_stacksAndQueues/fish.js: -------------------------------------------------------------------------------- 1 | // 75% 2 | function solution(A, B) { 3 | var done = false 4 | 5 | while (!done) { 6 | done = true 7 | 8 | for (var i = 0; i < A.length; i++) { 9 | 10 | if (B[i] === 1 && B[i+1] === 0) { 11 | done = false 12 | 13 | if (A[i] > A[i+1]) { 14 | A.splice(i+1, 1) 15 | B.splice(i+1, 1) 16 | } else { 17 | A.splice(i, 1) 18 | B.splice(i, 1) 19 | } 20 | } 21 | } 22 | } 23 | 24 | return A.length 25 | } 26 | 27 | // 100% - NEED TO REWRITE 28 | function solution(A, B) { 29 | var len = A.length 30 | var stack = [] 31 | 32 | for (var i = 0; i < len; i++) { 33 | var liveFish = i 34 | 35 | while (B[liveFish] === 0 && B[stack[stack.length-1]] === 1) { 36 | var otherFish = stack.pop() 37 | if (A[otherFish] > A[liveFish]) liveFish = otherFish 38 | } 39 | 40 | stack.push(liveFish) 41 | } 42 | 43 | return stack.length 44 | } 45 | 46 | module.exports = solution 47 | 48 | /* 49 | 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. 50 | 51 | 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. 52 | 53 | 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: 54 | 55 | 0 represents a fish flowing upstream, 56 | 1 represents a fish flowing downstream. 57 | 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: 58 | 59 | If A[P] > A[Q] then P eats Q, and P will still be flowing downstream, 60 | If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream. 61 | 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. 62 | 63 | For example, consider arrays A and B such that: 64 | 65 | A[0] = 4 B[0] = 0 66 | A[1] = 3 B[1] = 1 67 | A[2] = 2 B[2] = 0 68 | A[3] = 1 B[3] = 0 69 | A[4] = 5 B[4] = 0 70 | 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. 71 | 72 | Write a function: 73 | 74 | int solution(int A[], int B[], int N); 75 | that, given two non-empty zero-indexed arrays A and B consisting of N integers, returns the number of fish that will stay alive. 76 | 77 | For example, given the arrays shown above, the function should return 2, as explained above. 78 | 79 | Assume that: 80 | 81 | N is an integer within the range [1..100,000]; 82 | each element of array A is an integer within the range [0..1,000,000,000]; 83 | each element of array B is an integer that can have one of the following values: 0, 1; 84 | the elements of A are all distinct. 85 | Complexity: 86 | 87 | expected worst-case time complexity is O(N); 88 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 89 | Elements of input arrays can be modified. 90 | */ 91 | -------------------------------------------------------------------------------- /codility/10_primeAndCompositeNumbers/peaks-higher-neighbors.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(A) { 3 | var len = A.length 4 | var result = 0 5 | 6 | for (var d = 2; d <= len; d++) { 7 | if (len % d !== 0) continue; 8 | var peaksCount = 0 9 | 10 | for (var i = 0; i < len; i += d) { 11 | rangePeakFound = false 12 | 13 | for (var j = i; j < i+d; j++) { 14 | 15 | if (A[j] > A[j-1] && A[j] > A[j+1]) { 16 | rangePeakFound = true 17 | peaksCount++ 18 | break; 19 | } 20 | } 21 | 22 | if (!rangePeakFound) { 23 | peaksCount = 0 24 | break; 25 | } 26 | } 27 | 28 | if (peaksCount === len/d) { 29 | result = len/d 30 | break; 31 | } 32 | } 33 | 34 | return result 35 | } 36 | 37 | module.exports = solution 38 | 39 | /* 40 | A non-empty zero-indexed array A consisting of N integers is given. 41 | 42 | A peak is an array element which is larger than its neighbors. More precisely, it is an index P such that 0 < P < N − 1, A[P − 1] < A[P] and A[P] > A[P + 1]. 43 | 44 | For example, the following array A: 45 | 46 | A[0] = 1 47 | A[1] = 2 48 | A[2] = 3 49 | A[3] = 4 50 | A[4] = 3 51 | A[5] = 4 52 | A[6] = 1 53 | A[7] = 2 54 | A[8] = 3 55 | A[9] = 4 56 | A[10] = 6 57 | A[11] = 2 58 | has exactly three peaks: 3, 5, 10. 59 | 60 | 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: 61 | 62 | A[0], A[1], ..., A[K − 1], 63 | A[K], A[K + 1], ..., A[2K − 1], 64 | ... 65 | A[N − K], A[N − K + 1], ..., A[N − 1]. 66 | 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). 67 | 68 | The goal is to find the maximum number of blocks into which the array A can be divided. 69 | 70 | Array A can be divided into blocks as follows: 71 | 72 | one block (1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2). This block contains three peaks. 73 | two blocks (1, 2, 3, 4, 3, 4) and (1, 2, 3, 4, 6, 2). Every block has a peak. 74 | 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. 75 | 76 | 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]. 77 | 78 | The maximum number of blocks that array A can be divided into is three. 79 | 80 | Write a function: 81 | 82 | int solution(int A[], int N); 83 | 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. 84 | 85 | If A cannot be divided into some number of blocks, the function should return 0. 86 | 87 | For example, given: 88 | 89 | A[0] = 1 90 | A[1] = 2 91 | A[2] = 3 92 | A[3] = 4 93 | A[4] = 3 94 | A[5] = 4 95 | A[6] = 1 96 | A[7] = 2 97 | A[8] = 3 98 | A[9] = 4 99 | A[10] = 6 100 | A[11] = 2 101 | the function should return 3, as explained above. 102 | 103 | Assume that: 104 | 105 | N is an integer within the range [1..100,000]; 106 | each element of array A is an integer within the range [0..1,000,000,000]. 107 | Complexity: 108 | 109 | expected worst-case time complexity is O(N*log(log(N))); 110 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 111 | Elements of input arrays can be modified. 112 | */ -------------------------------------------------------------------------------- /codility/05_prefixSums/genomicRangeQuery.js: -------------------------------------------------------------------------------- 1 | // 100% 2 | function solution(S, P, Q) { 3 | S = S.split('') 4 | var Slen = S.length 5 | var Qlen = P.length 6 | var factors = ['A', 'C', 'G', 'T'] 7 | var sums = {} 8 | var results = [] 9 | 10 | for (var i = Slen-1; i >= 0; i--) { 11 | sums[i] = {} 12 | 13 | factors.forEach(f => { 14 | var next = i === Slen-1 ? 0 : sums[i+1][f] 15 | sums[i][f] = S[i] === f ? next+1 : next 16 | }) 17 | } 18 | 19 | for (var i = 0; i < Qlen; i++) { 20 | var start = P[i] 21 | var end = Q[i]+1 22 | var hasA = sums[start].A - (sums[end] ? sums[end].A : 0) 23 | var hasC = sums[start].C - (sums[end] ? sums[end].C : 0) 24 | var hasG = sums[start].G - (sums[end] ? sums[end].G : 0) 25 | 26 | if (hasA) { 27 | results.push(1) 28 | } else if (hasC) { 29 | results.push(2) 30 | } else if (hasG) { 31 | results.push(3) 32 | } else { 33 | results.push(4) 34 | } 35 | } 36 | 37 | return results 38 | } 39 | 40 | module.exports = solution 41 | 42 | /* 43 | 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? 44 | 45 | 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). 46 | 47 | For example, consider string S = CAGCCTA and arrays P, Q such that: 48 | 49 | P[0] = 2 Q[0] = 4 50 | P[1] = 5 Q[1] = 5 51 | P[2] = 0 Q[2] = 6 52 | The answers to these M = 3 queries are as follows: 53 | 54 | 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. 55 | The part between positions 5 and 5 contains a single nucleotide T, whose impact factor is 4, so the answer is 4. 56 | 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. 57 | Assume that the following declarations are given: 58 | 59 | struct Results { 60 | int * A; 61 | int M; 62 | }; 63 | Write a function: 64 | 65 | struct Results solution(char *S, int P[], int Q[], int M); 66 | 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. 67 | 68 | The sequence should be returned as: 69 | 70 | a Results structure (in C), or 71 | a vector of integers (in C++), or 72 | a Results record (in Pascal), or 73 | an array of integers (in any other programming language). 74 | For example, given the string S = CAGCCTA and arrays P, Q such that: 75 | 76 | P[0] = 2 Q[0] = 4 77 | P[1] = 5 Q[1] = 5 78 | P[2] = 0 Q[2] = 6 79 | the function should return the values [2, 4, 1], as explained above. 80 | 81 | Assume that: 82 | 83 | N is an integer within the range [1..100,000]; 84 | M is an integer within the range [1..50,000]; 85 | each element of arrays P, Q is an integer within the range [0..N − 1]; 86 | P[K] ≤ Q[K], where 0 ≤ K < M; 87 | string S consists only of upper-case English letters A, C, G, T. 88 | Complexity: 89 | 90 | expected worst-case time complexity is O(N+M); 91 | expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). 92 | Elements of input arrays can be modified. 93 | */ 94 | -------------------------------------------------------------------------------- /codility/tests.js: -------------------------------------------------------------------------------- 1 | // oddOccurrencesInArray 2 | describe('Algorithm', () => { 3 | 4 | it('is accurate', (done) => { 5 | var A = [] 6 | for (var i = 1; i <= 100000; i++) { 7 | var val = i%2 === 0 ? i : i+1 8 | A.push(val) 9 | if (i === 100000) A.push(200001) 10 | } 11 | 12 | expect(solution([1])).to.equal(1) 13 | expect(solution([9,3,9,3,9,7,9])).to.equal(7) 14 | expect(solution([9,3,9,3,9,3,9])).to.equal(3) 15 | expect(solution(A.slice(0))).to.equal(200001) 16 | expect(solution(_.reverse(A.slice(0)))).to.equal(200001) 17 | expect(solution(_.shuffle(A.slice(0)))).to.equal(200001) 18 | done() 19 | }) 20 | 21 | it('is fast', (done) => { 22 | var A = [] 23 | for (var i = 0; i < 1000000; i++) { 24 | A.push(i-5000) 25 | } 26 | 27 | time([ _.reverse(A.slice(0)) ]) 28 | time([ A.slice(0) ]) 29 | 30 | done() 31 | }) 32 | }) 33 | 34 | // permMissingElem 35 | describe('Algorithm', () => { 36 | 37 | it('is accurate', (done) => { 38 | expect(solution([])).to.equal(1) 39 | expect(solution([2])).to.equal(1) 40 | expect(solution([1])).to.equal(2) 41 | expect(solution([2, 3])).to.equal(1) 42 | expect(solution([1, 2])).to.equal(3) 43 | expect(solution([1, 2, 3, 4, 5])).to.equal(6) 44 | expect(solution([1, 2, 4, 5, 6])).to.equal(3) 45 | expect(solution([2, 3, 4, 5, 6])).to.equal(1) 46 | done() 47 | }) 48 | 49 | it('is fast', (done) => { 50 | var A = [] 51 | for (var i = 1; i < 100000; i++) { 52 | A.push(i) 53 | } 54 | 55 | time([ A.slice(0) ]) 56 | time([ _.shuffle(A.slice(0)) ]) 57 | 58 | done() 59 | }) 60 | }) 61 | 62 | // tapeEquilibrium 63 | describe('Algorithm', () => { 64 | 65 | it('is accurate', (done) => { 66 | expect(solution([3, 1, 2, 4, 3])).to.equal(1) 67 | expect(solution([2, 3])).to.equal(1) 68 | expect(solution([-30, 3])).to.equal(33) 69 | expect(solution([-50, 1, 2])).to.equal(51) 70 | expect(solution([1, 2, 4, 5, 6])).to.equal(4) 71 | done() 72 | }) 73 | 74 | it('is fast', (done) => { 75 | var A = [] 76 | for (var i = 1; i < 100000; i++) A.push(i) 77 | 78 | time([ A.slice(0) ]) 79 | time([ _.shuffle(A.slice(0)) ]) 80 | time([ _.reverse(A.slice(0)) ]) 81 | 82 | done() 83 | }) 84 | }) 85 | 86 | // frogRiverOne 87 | describe('Algorithm', () => { 88 | 89 | it('is accurate', (done) => { 90 | expect(solution(1, [1])).to.equal(0) 91 | expect(solution(2, [2])).to.equal(-1) 92 | expect(solution(2, [1, 1, 1, 1, 2, 1, 1 ,1])).to.equal(4) 93 | expect(solution(2, [2, 2, 1])).to.equal(2) 94 | expect(solution(5, [2, 3, 4, 5])).to.equal(-1) 95 | expect(solution(6, [1, 2, 3, 4, 5, 6])).to.equal(5) 96 | done() 97 | }) 98 | 99 | it('is fast', (done) => { 100 | var A = [] 101 | var leafs = [1, 2, 3, 4, 5, 6] 102 | for (var i = 0; i < 100000; i++) { 103 | A.push(_.sample(leafs)) 104 | } 105 | 106 | time([ 10, A.slice(0) ]) 107 | time([ 6, _.shuffle(A.slice(0)) ]) 108 | time([ 6, _.reverse(A.slice(0)) ]) 109 | 110 | done() 111 | }) 112 | }) 113 | 114 | // maxCounters 115 | describe('Algorithm', () => { 116 | 117 | it('is accurate', (done) => { 118 | expect(solution(1, [1])).to.deep.equal([1]) 119 | expect(solution(2, [1, 2, 3])).to.deep.equal([1, 1]) 120 | expect(solution(5, [3, 4, 4, 6, 1, 4, 4])).to.deep.equal([3, 2, 2, 4, 2]) 121 | expect(solution(5, [1, 1, 1, 1, 1, 1, 1])).to.deep.equal([7, 0, 0, 0, 0]) 122 | done() 123 | }) 124 | 125 | it('is fast', (done) => { 126 | var A = [] 127 | for (var j = 1; j <= 100000; j++) { 128 | A.push(_.random(0, 1) ? j : 100001) 129 | } 130 | 131 | time([ 100000, A.slice(0) ]) 132 | time([ 100000, _.shuffle(A.slice(0)) ]) 133 | time([ 100000, _.reverse(A.slice(0)) ]) 134 | 135 | done() 136 | }) 137 | }) 138 | 139 | // missingInteger 140 | describe('Algorithm', () => { 141 | 142 | it('is accurate', (done) => { 143 | expect(solution([1])).to.equal(2) 144 | expect(solution([1, 2, 3])).to.equal(4) 145 | expect(solution([3, 4, 4, 6, 1, 4, 4])).to.equal(2) 146 | expect(solution([3, 4, 4, 6, 1, 4, 4])).to.equal(2) 147 | expect(solution([1, 3, 6, 4, 1, 2])).to.equal(5) 148 | expect(solution([-2, 0])).to.equal(1) 149 | expect(solution([-2, -45])).to.equal(1) 150 | expect(solution([-2, -45, 0, 1, 2, 4])).to.equal(3) 151 | expect(solution([-2, -45, 0, 1, 2])).to.equal(3) 152 | done() 153 | }) 154 | 155 | it('is fast', (done) => { 156 | var A = [] 157 | for (var i = 1; i <= 100000; i++) { 158 | A.push(_.random(-434004330, 343434340)) 159 | } 160 | 161 | time([ A.slice(0) ]) 162 | time([ _.shuffle(A.slice(0)) ]) 163 | time([ _.reverse(A.slice(0)) ]) 164 | 165 | done() 166 | }) 167 | }) 168 | 169 | // permCheck 170 | describe('Algorithm', () => { 171 | 172 | it('is accurate', (done) => { 173 | expect(solution([1])).to.equal(1) 174 | expect(solution([1, 2, 3])).to.equal(1) 175 | expect(solution([4, 1, 3, 2])).to.equal(1) 176 | expect(solution([4, 1, 3])).to.equal(0) 177 | expect(solution([1, 2, 3, 4, 5, 7])).to.equal(0) 178 | expect(solution([2])).to.equal(0) 179 | expect(solution([2, 3])).to.equal(0) 180 | expect(solution([1, 2, 3, 40])).to.equal(0) 181 | expect(solution([1, 2, 3, 40, 41, 42])).to.equal(0) 182 | done() 183 | }) 184 | 185 | it('is fast', (done) => { 186 | var A = [] 187 | for (var i = 1; i <= 100000; i++) { 188 | A.push(i) 189 | } 190 | 191 | time([ A.slice(0) ]) 192 | time([ _.shuffle(A.slice(0)) ]) 193 | time([ _.reverse(A.slice(0)) ]) 194 | 195 | done() 196 | }) 197 | }) 198 | 199 | // countDiv 200 | describe('Algorithm', () => { 201 | 202 | it('is accurate', (done) => { 203 | expect(solution(6, 11, 2)).to.equal(3) 204 | expect(solution(0, 1, 1)).to.equal(2) 205 | expect(solution(0, 0, 1)).to.equal(1) 206 | expect(solution(0, 9, 3)).to.equal(4) 207 | expect(solution(1, 9, 3)).to.equal(3) 208 | expect(solution(1, 10, 1)).to.equal(10) 209 | expect(solution(1, 350, 7)).to.equal(50) 210 | expect(solution(0, 350, 20000000)).to.equal(1) 211 | expect(solution(1, 350, 20000000)).to.equal(0) 212 | done() 213 | }) 214 | }) 215 | 216 | // passingCars 217 | describe('Algorithm', () => { 218 | 219 | it('is accurate', (done) => { 220 | expect(solution([1])).to.equal(0) 221 | expect(solution([0])).to.equal(0) 222 | expect(solution([1, 1])).to.equal(0) 223 | expect(solution([0, 0])).to.equal(0) 224 | expect(solution([1, 1, 1, 0])).to.equal(0) 225 | expect(solution([1, 1, 0, 1])).to.equal(1) 226 | expect(solution([0, 1, 0, 1, 1])).to.equal(5) 227 | expect(solution([0, 1, 0, 1, 1])).to.equal(5) 228 | expect(solution([0, 1, 0, 1, 1, 1])).to.equal(7) 229 | expect(solution([1, 1, 0, 1, 1, 1])).to.equal(3) 230 | done() 231 | }) 232 | 233 | it('is fast', (done) => { 234 | var A = [] 235 | for (var i = 1; i <= 100000; i++) { 236 | A.push(_.random(0, 1)) 237 | } 238 | 239 | time([ A.slice(0) ]) 240 | 241 | done() 242 | }) 243 | }) 244 | 245 | // genomicRangeQuery 246 | describe('Algorithm', () => { 247 | 248 | it('is accurate', (done) => { 249 | expect(solution('CAGCCTA', [2, 5, 0], [4, 5, 6])).to.deep.equal([2, 4, 1]) 250 | expect(solution('A', [0], [0])).to.deep.equal([1]) 251 | expect(solution('AACCGGTT', [0, 2, 4, 6], [1, 3, 5, 7])).to.deep.equal([1, 2, 3, 4]) 252 | done() 253 | }) 254 | 255 | it('is fast', (done) => { 256 | var S = [] 257 | var factors = ['A', 'C', 'G', 'T'] 258 | for (var i = 1; i <= 100000; i++) { 259 | S.push(_.sample(factors)) 260 | } 261 | S = S.join('') 262 | 263 | var P = [] 264 | var Q = [] 265 | for (var i = 1; i <= 50000; i++) { 266 | P.push(_.random(1, 25000)) 267 | Q.push(_.random(25001, 50000)) 268 | } 269 | 270 | time([S, P, Q]) 271 | 272 | done() 273 | }) 274 | }) 275 | 276 | // arrSplitSameDiff 277 | describe('Algorithm', () => { 278 | 279 | it('is accurate', (done) => { 280 | expect(solution(5, [5, 5, 1, 7, 2, 3, 5])).to.equal(4) 281 | expect(solution(5, [5, 5, 3, 4])).to.equal(2) 282 | expect(solution(2, [2])).to.equal(0) 283 | done() 284 | }) 285 | }) 286 | 287 | // minAvgTwoSlice 288 | describe('Algorithm', () => { 289 | 290 | it('is accurate', (done) => { 291 | expect(solution([4, 2, 2, 5, 1, 5, 8])).to.equal(1) 292 | expect(solution([4, 2, 2, 5, 1, 5, 8, 0, 0, 10])).to.equal(7) 293 | expect(solution([5, 5, 3, 4])).to.equal(2) 294 | expect(solution([1, 2, 0, 0])).to.equal(2) 295 | expect(solution([-5, 10, 0, 1, 100, -50, 50])).to.equal(5) 296 | expect(solution([1, 2])).to.equal(0) 297 | done() 298 | }) 299 | 300 | it('is fast', (done) => { 301 | var A = [] 302 | for (var i = 1; i <= 100000; i++) { 303 | A.push(i) 304 | } 305 | 306 | time([A]) 307 | 308 | done() 309 | }) 310 | }) 311 | 312 | // triangle 313 | describe('Algorithm', () => { 314 | 315 | it('is accurate', (done) => { 316 | expect(solution([10, 2, 5, 1, 8, 20])).to.equal(1) 317 | expect(solution([10, 2])).to.equal(0) 318 | done() 319 | }) 320 | 321 | it('is fast', (done) => { 322 | var A = [] 323 | for (var i = 1; i <= 100000; i++) { 324 | A.push(i) 325 | } 326 | 327 | time([A]) 328 | 329 | done() 330 | }) 331 | }) 332 | 333 | // numberOfDiscIntersections 334 | describe('Algorithm', () => { 335 | 336 | it('is accurate', (done) => { 337 | expect(solution([])).to.equal(0) 338 | expect(solution([0, 1])).to.equal(1) 339 | expect(solution([0, 1, 2])).to.equal(3) 340 | expect(solution([0, 1, 2, 3, 4])).to.equal(10) 341 | expect(solution([1, 5, 2, 1, 4, 0])).to.equal(11) 342 | done() 343 | }) 344 | 345 | it('is fast', (done) => { 346 | var A = [] 347 | for (var i = 1; i <= 100000; i++) { 348 | A.push(_.random(0, 5)) 349 | } 350 | 351 | time([A]) 352 | 353 | done() 354 | }) 355 | }) 356 | 357 | // fish 358 | describe('Algorithm', () => { 359 | 360 | it('is accurate', (done) => { 361 | expect(solution([0], [0])).to.equal(1) 362 | expect(solution([3, 4], [0, 1])).to.equal(2) 363 | expect(solution([3, 4], [1, 0])).to.equal(1) 364 | expect(solution([3, 4, 5, 6], [1, 1, 1, 1])).to.equal(4) 365 | expect(solution([3, 4, 5, 6], [0, 0, 0, 0])).to.equal(4) 366 | expect(solution([4, 3, 2, 1, 5], [0, 1, 0, 0, 0])).to.equal(2) 367 | expect(solution([10, 3, 2, 1, 5], [1, 0, 0, 0, 0])).to.equal(1) 368 | done() 369 | }) 370 | 371 | it('is fast', (done) => { 372 | var A = [] 373 | var B = [] 374 | for (var i = 1; i <= 100000; i++) { 375 | A.push(_.random(0, 1000000000)) 376 | B.push(_.random(0, 1)) 377 | } 378 | 379 | time([A, B]) 380 | 381 | done() 382 | }) 383 | }) 384 | 385 | // brackets 386 | describe('Algorithm', () => { 387 | 388 | it('is accurate', (done) => { 389 | expect(solution('')).to.equal(1) 390 | expect(solution('{[()()]}')).to.equal(1) 391 | expect(solution('[)()]')).to.equal(0) 392 | expect(solution('[()](')).to.equal(0) 393 | expect(solution(')[()]')).to.equal(0) 394 | expect(solution('{([)()]}')).to.equal(0) 395 | expect(solution('{[(())]})')).to.equal(0) 396 | expect(solution('()()()()()')).to.equal(1) 397 | expect(solution('(((())))')).to.equal(1) 398 | done() 399 | }) 400 | 401 | it('is fast', (done) => { 402 | var A = [] 403 | var sample = ['(){}[]'] 404 | for (var i = 1; i <= 200000; i++) A.push(_.sample(sample)) 405 | 406 | var B = [] 407 | for (var i = 1; i <= 100000; i++) B.push('(') 408 | for (var i = 1; i <= 100000; i++) B.push(')') 409 | 410 | time([A.join('')]) 411 | time([B.join('')]) 412 | 413 | done() 414 | }) 415 | }) 416 | 417 | // stoneWall 418 | describe('Algorithm', () => { 419 | 420 | it('is accurate', (done) => { 421 | expect(solution([1])).to.equal(1) 422 | expect(solution([1, 2])).to.equal(2) 423 | expect(solution([3, 1, 3])).to.equal(3) 424 | expect(solution([2, 3, 2, 3])).to.equal(3) 425 | expect(solution([8, 8, 5, 7, 9, 8, 7, 4, 8])).to.equal(7) 426 | done() 427 | }) 428 | 429 | it('is fast', (done) => { 430 | var A = [] 431 | for (var i = 1; i <= 100000; i++) { 432 | A.push(i) 433 | } 434 | 435 | time([A]) 436 | 437 | done() 438 | }) 439 | }) 440 | 441 | // nesting 442 | describe('Algorithm', () => { 443 | 444 | it('is accurate', (done) => { 445 | expect(solution('')).to.equal(1) 446 | expect(solution('()()')).to.equal(1) 447 | expect(solution('()(')).to.equal(0) 448 | expect(solution(')()')).to.equal(0) 449 | expect(solution('((()')).to.equal(0) 450 | expect(solution('()())')).to.equal(0) 451 | expect(solution(')((())')).to.equal(0) 452 | expect(solution(')(')).to.equal(0) 453 | expect(solution('())(()')).to.equal(0) 454 | expect(solution('())(')).to.equal(0) 455 | expect(solution('(((())))')).to.equal(1) 456 | done() 457 | }) 458 | 459 | it('is fast', (done) => { 460 | var A = [] 461 | var sample = ['()'] 462 | for (var i = 1; i <= 200000; i++) A.push(_.sample(sample)) 463 | 464 | var B = [] 465 | for (var i = 1; i <= 100000; i++) B.push('(') 466 | for (var i = 1; i <= 100000; i++) B.push(')') 467 | 468 | time([A.join('')]) 469 | time([B.join('')]) 470 | 471 | done() 472 | }) 473 | }) 474 | 475 | // equiLeader 476 | describe('Algorithm', () => { 477 | 478 | it('is accurate', (done) => { 479 | expect(solution([4, 3, 4, 4, 4, 2])).to.equal(2) 480 | expect(solution([1, 1])).to.equal(1) 481 | expect(solution([-50, 1])).to.equal(0) 482 | expect(solution([2, 1, 5])).to.equal(0) 483 | expect(solution([1, 1, 1, 1, 1])).to.equal(4) 484 | expect(solution([1])).to.equal(0) 485 | done() 486 | }) 487 | 488 | it('is fast', (done) => { 489 | var A = [] 490 | for (var i = 1; i <= 100000; i++) { 491 | A.push(i) 492 | } 493 | 494 | time([A]) 495 | 496 | done() 497 | }) 498 | }) 499 | 500 | // dominator 501 | describe('Algorithm', () => { 502 | 503 | it('is accurate', (done) => { 504 | expect(solution([3, 4, 3, 2, 3, -1, 3, 3])).to.be.oneOf([0, 2, 4, 6, 7]) 505 | expect(solution([3, 3, 4, 3, 2, 3, -1])).to.be.oneOf([0, 1, 3, 5]) 506 | expect(solution([])).to.equal(-1) 507 | expect(solution([1])).to.equal(0) 508 | expect(solution([-50, 1])).to.equal(-1) 509 | expect(solution([2, 1, 5])).to.equal(-1) 510 | expect(solution([1, 1, 1, 1, 1])).to.be.oneOf([0, 1, 2, 3, 4]) 511 | done() 512 | }) 513 | 514 | it('is fast', (done) => { 515 | var A = [] 516 | for (var i = 1; i <= 100000; i++) { 517 | A.push(i) 518 | } 519 | 520 | time([A]) 521 | 522 | done() 523 | }) 524 | }) 525 | 526 | // maxProfit 527 | describe('Algorithm', () => { 528 | 529 | it('is accurate', (done) => { 530 | expect(solution([23171,21011,21123,21366,21013,21367])).to.equal(356) 531 | expect(solution([])).to.equal(0) 532 | expect(solution([1])).to.equal(0) 533 | expect(solution([1, 2])).to.equal(1) 534 | expect(solution([1, 2, 3])).to.equal(2) 535 | expect(solution([3, 3])).to.equal(0) 536 | expect(solution([3, 1])).to.equal(0) 537 | done() 538 | }) 539 | 540 | it('is fast', (done) => { 541 | var A = [] 542 | for (var i = 1; i <= 400000; i++) { 543 | A.push(i) 544 | } 545 | 546 | time([A]) 547 | 548 | done() 549 | }) 550 | }) 551 | 552 | // maxDoubleSliceSum 553 | describe('Algorithm', () => { 554 | 555 | it('is accurate', (done) => { 556 | expect(solution([3, 2, 6, -1, 4, 5, -1, 2])).to.equal(17) 557 | done() 558 | }) 559 | 560 | it('is fast', (done) => { 561 | var A = [] 562 | for (var i = 1; i <= 100000; i++) { 563 | A.push(i) 564 | } 565 | 566 | time([A]) 567 | 568 | done() 569 | }) 570 | }) 571 | 572 | // maxSliceSum 573 | describe('Algorithm', () => { 574 | 575 | it('is accurate', (done) => { 576 | expect(solution([6])).to.equal(6) 577 | expect(solution([-5])).to.equal(-5) 578 | expect(solution([1, 2, 3])).to.equal(6) 579 | expect(solution([3, 2, -6, 4, 0])).to.equal(5) 580 | expect(solution([6, 2, -100, 10])).to.equal(10) 581 | expect(solution([-5, -10, 1, -15])).to.equal(1) 582 | expect(solution([-5, -10, -1, -15])).to.equal(-1) 583 | done() 584 | }) 585 | 586 | it('is fast', (done) => { 587 | var A = [] 588 | for (var i = 1; i <= 1000000; i++) { 589 | A.push(_.random(-1000000, 1000000)) 590 | } 591 | 592 | time([A]) 593 | 594 | done() 595 | }) 596 | }) 597 | 598 | // minPerimeterRectangle 599 | describe('Algorithm', () => { 600 | 601 | it('is accurate', (done) => { 602 | expect(solution(30)).to.equal(22) 603 | expect(solution(16)).to.equal(16) 604 | expect(solution(1)).to.equal(4) 605 | expect(solution(2)).to.equal(6) 606 | done() 607 | }) 608 | 609 | it('is fast', (done) => { 610 | time([1000000000]) 611 | done() 612 | }) 613 | }) 614 | 615 | // countFactors 616 | describe('Algorithm', () => { 617 | 618 | it('is accurate', (done) => { 619 | expect(solution(24)).to.equal(8) 620 | expect(solution(1)).to.equal(1) 621 | expect(solution(2)).to.equal(2) 622 | expect(solution(3)).to.equal(2) 623 | expect(solution(12)).to.equal(6) 624 | expect(solution(2147483647)).to.equal(2) 625 | done() 626 | }) 627 | 628 | it('is fast', (done) => { 629 | time([2147483647]) 630 | done() 631 | }) 632 | }) 633 | 634 | // peaks 635 | describe('Algorithm', () => { 636 | 637 | it('is accurate', (done) => { 638 | expect(solution([1])).to.equal(0) 639 | expect(solution([1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2])).to.equal(3) 640 | expect(solution([1, 2, 1, 2, 1, 1])).to.equal(2) 641 | expect(solution([1, 2, 1, 2, 1])).to.equal(1) 642 | expect(solution([1, 1, 1, 2, 1, 1])).to.equal(1) 643 | done() 644 | }) 645 | 646 | it('is fast', (done) => { 647 | var A = [] 648 | for (var i = 1; i <= 100000; i++) { 649 | A.push(_.random(0, 1)) 650 | } 651 | 652 | time([A]) // 2.5s is ok 653 | }) 654 | }) 655 | 656 | // flags 657 | describe('Algorithm', () => { 658 | 659 | it('is accurate', (done) => { 660 | expect(solution([1])).to.equal(0) 661 | expect(solution([1, 5, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2])).to.equal(3) 662 | expect(solution([1, 2, 1, 2, 1, 1])).to.equal(2) 663 | expect(solution([1, 2, 1, 2, 1])).to.equal(2) 664 | expect(solution([1, 1, 1, 2, 1, 1])).to.equal(1) 665 | expect(solution([1, 2, 1, 2, 1, 2, 1])).to.equal(2) 666 | done() 667 | }) 668 | 669 | it('is fast', (done) => { 670 | var A = [] 671 | for (var i = 1; i <= 400000; i++) { 672 | A.push(_.random(0, 100000000)) // 2.5s is ok 673 | } 674 | 675 | time([A]) 676 | done() 677 | }) 678 | }) 679 | 680 | // countSemiPrimes 681 | describe('Algorithm', () => { 682 | 683 | it('is accurate', (done) => { 684 | expect(solution(26, [1, 4, 16], [26, 10, 20])).to.deep.equal([10, 4, 0]) 685 | expect(solution(2, [1], [1])).to.deep.equal([0]) 686 | expect(solution(10, [1], [10])).to.deep.equal([4]) 687 | expect(solution(10, [4], [4])).to.deep.equal([1]) 688 | done() 689 | }) 690 | 691 | it('is fast', (done) => { 692 | var P = [] 693 | var Q = [] 694 | for (var i = 1; i <= 30000; i++) { 695 | P.push(0) 696 | Q.push(50000) 697 | } 698 | 699 | time([50000, P, Q]) 700 | done() 701 | }) 702 | }) 703 | 704 | // countNonDivisible 705 | describe('Algorithm', () => { 706 | 707 | it('is accurate', (done) => { 708 | expect(solution([1])).to.deep.equal([0]) 709 | expect(solution([1, 2])).to.deep.equal([1, 0]) 710 | expect(solution([1, 2, 3, 4])).to.deep.equal([3, 2, 2, 1]) 711 | expect(solution([9, 6, 7, 10, 6])).to.deep.equal([4, 3, 4, 4, 3]) 712 | expect(solution([3, 1, 2, 3, 6])).to.deep.equal([2, 4, 3, 2, 0]) 713 | done() 714 | }) 715 | 716 | it('is fast', (done) => { 717 | var A = [] 718 | for (var i = 1; i <= 50000; i++) { 719 | A.push(_.random(1, 2*50000)) 720 | } 721 | 722 | time([A]) 723 | done() 724 | }) 725 | }) 726 | 727 | // chocolatesByNumbers 728 | describe('Algorithm', () => { 729 | 730 | it('is accurate', (done) => { 731 | expect(solution(10, 4)).to.equal(5) 732 | expect(solution(10, 10)).to.equal(1) 733 | done() 734 | }) 735 | 736 | it('is fast', (done) => { 737 | time([10000000, 1]) 738 | done() 739 | }) 740 | }) 741 | 742 | // commonPrimeDivisors 743 | describe('Algorithm', () => { 744 | 745 | it('is accurate', (done) => { 746 | expect(solution([2, 3, 4], [2, 3, 5])).to.equal(2) 747 | expect(solution([15, 10, 3], [75, 30, 5])).to.equal(1) 748 | done() 749 | }) 750 | 751 | it('is fast', (done) => { 752 | var A = [] 753 | var B = [] 754 | for (var i = 1; i <= 6000; i++) { 755 | A.push(2147483647) 756 | B.push(2147483647) 757 | } 758 | 759 | time([A, B]) 760 | done() 761 | }) 762 | }) 763 | 764 | // fibFrog 765 | describe('Algorithm', () => { 766 | 767 | it('is accurate', (done) => { 768 | expect(solution([])).to.equal(1) 769 | expect(solution([0])).to.equal(1) 770 | expect(solution([0, 0, 0])).to.equal(-1) 771 | expect(solution([0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0])).to.equal(3) 772 | expect(solution([0, 0, 0, 0])).to.equal(1) 773 | expect(solution([1, 0, 0, 1, 0, 1])).to.equal(3) 774 | expect(solution([1, 1, 1, 1, 1, 0, 0, 0])).to.equal(3) 775 | done() 776 | }) 777 | 778 | it('is fast', (done) => { 779 | var A = [] 780 | for (var i = 1; i <= 100000; i++) { 781 | A.push(_.random(0, 1)) 782 | } 783 | 784 | time([A]) 785 | done() 786 | }) 787 | }) 788 | 789 | // minMaxDivision 790 | describe('Algorithm', () => { 791 | 792 | it('is accurate', (done) => { 793 | expect(solution(3, 5, [2, 1, 5, 1, 2, 2, 2])).to.equal(6) 794 | expect(solution(3, 0, [0, 0, 0, 0, 0, 0])).to.equal(0) 795 | expect(solution(3, 5, [0, 5, 5, 0, 5, 0])).to.equal(5) 796 | expect(solution(3, 5, [5, 5, 5, 5, 0, 0])).to.equal(10) 797 | expect(solution(2, 5, [-5, 5, -5, 5])).to.equal(0) 798 | expect(solution(2, 3, [3])).to.equal(3) 799 | done() 800 | }) 801 | 802 | it('is fast', (done) => { 803 | var A = [] 804 | var sample = [0, 500] 805 | for (var i = 1; i <= 100000; i++) { 806 | A.push(_.sample(sample)) 807 | } 808 | 809 | time([20, 500, A]) 810 | done() 811 | }) 812 | }) 813 | 814 | // nailingPlanks 815 | describe('Algorithm', () => { 816 | 817 | it('is accurate', (done) => { 818 | expect(solution([1, 4, 5, 8], [4, 5, 9, 10], [4, 6, 7, 10, 2])).to.equal(4) 819 | expect(solution([1], [1], [2])).to.equal(-1) 820 | done() 821 | }) 822 | 823 | it('is fast', (done) => { 824 | var A = [] 825 | var B = [] 826 | var C = [] 827 | for (var i = 1; i <= 30000; i++) { 828 | A.push(i) 829 | B.push(i) 830 | C.push(_.random(1, 60000)) 831 | } 832 | 833 | time([A, B, C]) 834 | done() 835 | }) 836 | }) 837 | 838 | // countDistinctSlices 839 | describe('Algorithm', () => { 840 | 841 | it('is accurate', (done) => { 842 | expect(solution(6, [3, 4, 5, 5, 2])).to.equal(9) 843 | expect(solution(10, [1, 2, 3])).to.equal(6) 844 | expect(solution(10, [1])).to.equal(1) 845 | expect(solution(10, [1, 1, 1, 1])).to.equal(4) 846 | done() 847 | }) 848 | 849 | it('is fast', (done) => { 850 | var A = [] 851 | for (var i = 1; i <= 100000; i++) { 852 | A.push(i) 853 | } 854 | 855 | time([100000, A]) 856 | done() 857 | }) 858 | }) 859 | 860 | // countTriangles 861 | describe('Algorithm', () => { 862 | 863 | it('is accurate', (done) => { 864 | expect(solution([10, 2, 5, 1, 8, 12])).to.equal(4) 865 | expect(solution([1])).to.equal(0) 866 | done() 867 | }) 868 | 869 | it('is fast', (done) => { 870 | var A = [] 871 | for (var i = 1; i <= 1000; i++) { 872 | A.push(_.random(1, 1000000000)) 873 | } 874 | 875 | time([A]) 876 | done() 877 | }) 878 | }) 879 | 880 | // absDistinct 881 | describe('Algorithm', () => { 882 | 883 | it('is accurate', (done) => { 884 | expect(solution([1, 2, 3, 4, 5])).to.equal(5) 885 | expect(solution([1, 2, 3, -4, -5])).to.equal(5) 886 | expect(solution([1, 5, 4, -4, -5])).to.equal(3) 887 | done() 888 | }) 889 | 890 | it('is fast', (done) => { 891 | var A = [] 892 | for (var i = 1; i <= 100000; i++) { 893 | A.push(i) 894 | } 895 | 896 | time([A]) 897 | done() 898 | }) 899 | }) 900 | 901 | // minAbsSumOfTwo 902 | describe('Algorithm', () => { 903 | 904 | it('is accurate', (done) => { 905 | expect(solution([5])).to.equal(10) 906 | expect(solution([-5])).to.equal(10) 907 | expect(solution([1, 4])).to.equal(2) 908 | expect(solution([-1, -4])).to.equal(2) 909 | expect(solution([4, -4])).to.equal(0) 910 | expect(solution([1, 4, -3])).to.equal(1) 911 | expect(solution([10, 15, 20, -1])).to.equal(2) 912 | expect(solution([10, -15, 1, 1])).to.equal(2) 913 | expect(solution([-8, 4, 5, -10, 3])).to.equal(3) 914 | done() 915 | }) 916 | 917 | it('is fast', (done) => { 918 | var A = [] 919 | for (var i = 1; i <= 100000; i++) { 920 | A.push(_.random(-1000000000, 1000000000)) 921 | } 922 | 923 | time([A]) 924 | done() 925 | }) 926 | }) 927 | 928 | // maxNonoverlappingSegments 929 | describe('Algorithm', () => { 930 | 931 | it('is accurate', (done) => { 932 | expect(solution([])).to.equal(0) 933 | expect(solution([1], [1])).to.equal(1) 934 | expect(solution([3, 3, 3], [3, 3, 3])).to.equal(1) 935 | expect(solution([1, 3, 7, 9, 9], [5, 6, 8, 9, 10])).to.equal(3) 936 | expect(solution([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])).to.equal(5) 937 | expect(solution([1, 2, 3, 4, 5], [1, 2, 3, 5, 5])).to.equal(4) 938 | done() 939 | }) 940 | 941 | it('is fast', (done) => { 942 | var A = [] 943 | var B = [] 944 | for (var i = 1; i <= 30000; i++) { 945 | A.push(i) 946 | B.push(i) 947 | } 948 | 949 | time([A, B]) 950 | done() 951 | }) 952 | }) 953 | 954 | // tieRopes 955 | describe('Algorithm', () => { 956 | 957 | it('is accurate', (done) => { 958 | expect(solution(5, [2])).to.equal(0) 959 | expect(solution(5, [5])).to.equal(1) 960 | expect(solution(5, [5, 4])).to.equal(1) 961 | expect(solution(5, [5, 5])).to.equal(2) 962 | expect(solution(4, [1, 2, 3, 4, 1, 1 ,3])).to.equal(3) 963 | expect(solution(5, [4, 4, 1, 3 ])).to.equal(1) 964 | done() 965 | }) 966 | 967 | it('is fast', (done) => { 968 | var A = [] 969 | for (var i = 1; i <= 100000; i++) { 970 | A.push(i) 971 | } 972 | 973 | time([2000, A]) 974 | done() 975 | }) 976 | }) 977 | 978 | // numberSolitaire 979 | describe('Algorithm', () => { 980 | 981 | it('is accurate', (done) => { 982 | expect(solution([1, -2, 0, 9, -1, -2])).to.equal(8) 983 | expect(solution([1, 2])).to.equal(3) 984 | done() 985 | }) 986 | 987 | it('is fast', (done) => { 988 | var A = [] 989 | for (var i = 1; i <= 100000; i++) { 990 | A.push(i) 991 | } 992 | 993 | time([A]) 994 | done() 995 | }) 996 | }) 997 | 998 | // treeHeight 999 | describe('Algorithm', () => { 1000 | 1001 | var T1 = { x: 5, 1002 | l: { x: 3, 1003 | l: { x: 20, l: null, r: null }, 1004 | r: { x: 21, l: null, r: { x: 5, 1005 | l: { x: 3, 1006 | l: { x: 20, l: null, r: null }, 1007 | r: { x: 21, l: null, r: null } }, 1008 | r: { x: 10, l: { x: 1, l: null, r: null }, r: null } 1009 | } } }, 1010 | r: { x: 10, l: { x: 1, l: null, r: null }, r: null } 1011 | } 1012 | 1013 | var T2 = { 1014 | l: null, 1015 | r: null 1016 | } 1017 | 1018 | it('is accurate', (done) => { 1019 | expect(solution(T1)).to.equal(5) 1020 | expect(solution(T2)).to.equal(0) 1021 | done() 1022 | }) 1023 | }) 1024 | 1025 | // strSymmetryPoint 1026 | describe('Algorithm', () => { 1027 | 1028 | it('is accurate', (done) => { 1029 | expect(solution('racecar')).to.equal(3) 1030 | expect(solution('aba')).to.equal(1) 1031 | expect(solution('ab')).to.equal(-1) 1032 | expect(solution('racecra')).to.equal(-1) 1033 | expect(solution('x')).to.equal(0) 1034 | expect(solution('')).to.equal(-1) 1035 | done() 1036 | }) 1037 | }) --------------------------------------------------------------------------------