Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Codility Solutions in JavaScript
Lesson 1 - Iterations
- BinaryGap - https://codility.com/demo/results/trainingU2FQPQ-7Y4/
Lesson 2 - Arrays
- OddOccurrencesInArray - https://codility.com/demo/results/trainingFN5RVT-XQ4/
- CyclicRotation - https://codility.com/demo/results/trainingSH2W5R-RP5/
Lesson 3 - Time Complexity
- FrogJmp - https://codility.com/demo/results/training6KKWUD-BXJ/
- PermMissingElem - https://codility.com/demo/results/training58W4YJ-VHA/
- TapeEquilibrum - https://codility.com/demo/results/trainingHMJHCT-9BX/
Lesson 4 - Couting Elements
- MissingInteger - https://codility.com/demo/results/trainingPBJ5G7-2QB/
- FrogRiverOne - https://codility.com/demo/results/trainingVKFWNJ-84P/
- PermCheck - https://codility.com/demo/results/trainingN4XJDP-QJ6/
- MaxCounters - https://codility.com/demo/results/trainingQ3KEC6-S4T/
Lesson 5 - Prefix Sums
- CountDiv - https://codility.com/demo/results/trainingGBF99N-YHX/
- PassingCars - https://codility.com/demo/results/trainingAR78MG-6TF/
- GenomicRangeQuery - https://codility.com/demo/results/trainingZ47Q2A-CUW/
- MinAvgTwoSlice - https://codility.com/demo/results/trainingU6BWPU-ADW/
Lesson 6 - Sorting
- Triangle - https://codility.com/demo/results/training5FCWC6-F95/
- Distinct - https://codility.com/demo/results/trainingWPEYF6-TC9/
- MaxProductOfThree - https://codility.com/demo/results/trainingR637FP-8XS/
- NumberOfDiscIntersections - https://codility.com/demo/results/trainingDQZTYA-ZGD/
Lesson 7 - Stacks and Queues
- Brackets - https://codility.com/demo/results/trainingRQ4V9Q-PWX/
- Fish - https://codility.com/demo/results/trainingYGH5E7-N5G/
- StoneWall - https://codility.com/demo/results/trainingYYWY68-ZVH/
- Nesting - https://codility.com/demo/results/trainingV9B3AN-2QW/
Lesson 8 - Leader
- EquiLeader - https://codility.com/demo/results/trainingV5AZPJ-J9X/
- Dominator - https://codility.com/demo/results/trainingKNH5G4-FX9/
Lesson 9 - Maximum slice problem
- MaxDoubleSliceSum - https://codility.com/demo/results/trainingUY3GP9-J3Q/
- MaxProfit - https://codility.com/demo/results/training34TMJW-JT9/
- MaxSliceSum - https://codility.com/demo/results/trainingTXHJSZ-DXF/
Lesson 10 - Prime and composite numbers
- MinPerimeterRectangle - https://codility.com/demo/results/trainingW4XUWT-EXR/
- CountFactors - https://codility.com/demo/results/trainingGU5FEX-WD4/
- Flags - https://codility.com/demo/results/training97DBAE-GKV/
- Peaks - https://codility.com/demo/results/training7GBTZ2-BNT/
Lesson 11 - Sieve of Eratosthenes
- CountSemiprimes - https://codility.com/demo/results/trainingGFFQAS-GK8/
- CountNonDivisible - https://codility.com/demo/results/trainingUMCZ3V-9Q5/
Lesson 12 - Euclidean algorithm
- ChocolatesByNumber - https://codility.com/demo/results/trainingSXZ3KT-MV4/
- CommonPrimeDivisors - https://codility.com/demo/results/training9X2VFQ-6HC/
Lesson 13 - Fibonacci numbers
- FibFrog - https://codility.com/demo/results/trainingUZV28E-F7P/
- Ladder - https://codility.com/demo/results/trainingZXRA9N-33G/
Lesson 14 - Binary search algorithm
- MinMaxDivision - https://codility.com/demo/results/trainingHA5ZGD-H6G/
- NailingPlanks - https://codility.com/demo/results/trainingEW83KS-F3M/
Lesson 15 - Caterpillar method
- AbsDistinct - https://codility.com/demo/results/training4FP643-CE7/
- CountDistinctSlices - https://codility.com/demo/results/training3J563K-4GU/
- CountTriangles - https://codility.com/demo/results/trainingSREAJE-B4Q/
- MinAbsSumOfTwo - https://codility.com/demo/results/trainingPWSPFF-2X9/
Lesson 16 - Greedy algorithms
- MaxNonoverlappingSegments - https://codility.com/demo/results/training2XWCQT-MHR/
- TieRopes - https://codility.com/demo/results/trainingG9UHPH-8EX/
Lesson 17 - Dynamic programming
- NumberSolitaire - https://codility.com/demo/results/trainingXKAYAB-KGV/
- MinAbsSum - https://codility.com/demo/results/trainingQ7CF2B-9XJ/
Lesson 99 - Future training
- StrSymmetryPoint - https://codility.com/demo/results/training5SAKFX-JZ9/
- TreeHeight - https://codility.com/demo/results/training5M9QX5-CXQ/
- ArrayInversionCount - https://codility.com/demo/results/trainingZH3YMZ-D8H/ ************************** WIP
- PolygonConcavityIndex - https://codility.com/demo/results/trainingDRRKK2-Z57/
Challenges
- Alpha2010 - PrefixSet - https://codility.com/demo/results/trainingMACGW7-JXB/
- Beta 2010 - NumberOfDiscIntersections - https://codility.com/demo/results/trainingDQZTYA-ZGD/
- Gamma 2011 - CountPalindromicSlices - https://codility.com/demo/results/training4WWPKZ-9YD/ ************************** WIP
- Delta 2011 - MinAbsSum -https://codility.com/demo/results/trainingQ7CF2B-9XJ/
- Epsilon 2011 - Minfuds - https://codility.com/demo/results/trainingJE6X26-DKQ/ ************************** WIP
- Zeta 2011 - BallSwitchBoard - https://codility.com/demo/results/training9RCK8F-JBP/ ************************** WIP
- Eta 2011 - HamiltonianRoutesCount - https://codility.com/programmers/task/hamiltonian_routes_count/
- Theta 2011 - GasStations - https://codility.com/programmers/task/gas_stations/
- Iota 2011 - ShortestAdjSeq - https://codility.com/programmers/task/shortest_adj_seq/
- Kappa 2011 - SpaceCrews - https://codility.com/programmers/task/space_crews/
- Lambda 2011 - MinRouterPeripherality - https://codility.com/programmers/task/min_router_peripherality/
- Mu 2011 - NumberOfZeros - https://codility.com/programmers/task/number_of_zeros/
- Nu 2011 - DoubleMedian - https://codility.com/programmers/task/double_median/
- Xi 2012 - KSparseBinaryCount - https://codility.com/programmers/task/k_sparse_binary_count/
- Omicron 2012 - PowerFib - https://codility.com/programmers/task/power_fib/
- Pi 2012 - ArrayClosestAscenders - https://codility.com/programmers/task/array_closest_ascenders/
- Rho 2012 - HitTheNumber - https://codility.com/programmers/task/hit_the_number/
- Sigma 2012 - StoneWall - https://codility.com/demo/results/trainingYYWY68-ZVH/
- Tau 2012 - TorusLot - https://codility.com/programmers/task/torus_lot/
- Upsilon 2012 - CartesianSequence - https://codility.com/programmers/task/cartesian_sequence/
- Phi 2012 - TilingsCount - https://codility.com/programmers/task/tilings_count/
- Chi 2012 - Cannonballs - https://codility.com/programmers/task/cannonballs/
- Psi 2012 - WireBurnouts - https://codility.com/programmers/task/wire_burnouts/
- Omega 2013 - FallingDisks - https://codility.com/programmers/task/falling_disks/
- Hydrogenium 2013 - GroceryStore - https://codility.com/programmers/task/grocery_store/
- Helium 2013 - FindThree - https://codility.com/programmers/task/find_three/
- Lithium 2013 - Clocks - https://codility.com/programmers/task/clocks/
- Beryllium 2013 - PrefixSuffixSet - https://codility.com/programmers/task/prefix_suffix_set/
- Boron 2013 - Flags - https://codility.com/demo/results/training97DBAE-GKV/
- Carbo 2013 - PrefixMaxProduct - https://codility.com/programmers/task/prefix_max_product/
- Nitrogenium 2013 - FloodedIsland - https://codility.com/programmers/task/flooded_island/
- Oxygenium 2014 - CountBoundedSlices - https://codility.com/programmers/task/count_bounded_slices/
- Fluorum 2014 - TripPlanning - https://codility.com/programmers/task/trip_planning/
- Neon 2014 - BoatAlignment - https://codility.com/programmers/task/boat_alignment/
- Natrium 2014 - MaxDistanceMonotonic - https://codility.com/programmers/task/max_distance_monotonic/
- Magnesium 2014 - AscendingPaths - https://codility.com/programmers/task/ascending_paths/
- Aluminium 2014 - MaxSliceSwap - https://codility.com/programmers/task/max_slice_swap/
- Silicium 2014 - CuttingTheCake - https://codility.com/programmers/task/cutting_the_cake/
- Phosphorus 2014 - PrisonEscape - https://codility.com/programmers/task/prison_escape/
- Sulphur 2014 - BreakTheRope - https://codility.com/programmers/task/break_the_rope/
- Chlorum 2014 - TreeTrip - https://codility.com/programmers/task/tree_trip/
- Argon 2015 - TrekAndSwim - https://codility.com/programmers/task/trek_and_swim/
- Kalium 2015 - SqlSegmentSum - https://codility.com/programmers/task/sql_segments_sum/
- Calcium 2015 - SpeedCameras - https://codility.com/programmers/task/speed_cameras/
@inovramadani

This comment has been minimized.

Copy link

@inovramadani inovramadani commented May 15, 2017

Hi Lalkmim, I think the solution for Lesson 4 - FrogRiverOne should be like this:
https://codility.com/demo/results/trainingWE8NJA-YSE/

We will only return -1 if its not sufficient leaves to cross the river, so shouldn't it be "leaves.length< X" rather than "leaves.length<=X"? Somehow both code will return 100 score because no test case that breaks it.

Thanks for sharing the codility answer in javascript btw, it's really helpful!

Cheers from Indonesia.. :)

@rabbishuki

This comment has been minimized.

Copy link

@rabbishuki rabbishuki commented Dec 7, 2017

First of all, thanks.

It is a great idea to put your own solutions here, and I copied the idea with my solutions.

By the way, In lesson 3 - FrogJmp there is a much simpler solution.

instead of all the if & elses you can just return Math.ceil((Y - X) / D);

Check it out: https://codility.com/demo/results/training8KPF38-YJK/

@nkreiger

This comment has been minimized.

Copy link

@nkreiger nkreiger commented Jul 7, 2018

LOVE THIS!
Note Lesson 3 - TapeEquilibrium
A simpler way to do it with higher-order functions.

function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
var reducer = (accumulator, currentValue) => accumulator + currentValue;
var sum = A.reduce(reducer) - A[0];
var arrSum = 0;
var min = Math.abs(A[0] - sum);

for (var i = 0; i < A.length - 1; i++) {
    arrSum = arrSum + A[i];
    var diff = Math.abs(arrSum - sum);
    sum = sum - A[i + 1];
    if (diff < min) {
        min = diff;
    }
}
return min;

}

idk why it pastes like this every time
https://app.codility.com/demo/results/trainingHQRMXH-P6C/

@HusDev

This comment has been minimized.

Copy link

@HusDev HusDev commented Nov 1, 2018

Thanks Lilkimim,
Can you explain "OddOccurrencesInArray" to me, why it works?
I didn't understand this part:
agg ^= A[i];

@Synkevych

This comment has been minimized.

Copy link

@Synkevych Synkevych commented Nov 7, 2018

it is operator ХОР, if you try to transmit two equal numbers, you get 0, if you have 1 number without pair XOR return them.
Simple:
bar = 5; //00000000000000000000000000000101
bar ^= 5; // 00000000000000000000000000000101
//bar = 0, or 00000000000000000000000000000000

bar = 5;
bar ^= 2; // 7
// 5: 00000000000000000000000000000101
// 2: 00000000000000000000000000000010
// 7: 00000000000000000000000000000111

@leilenah

This comment has been minimized.

Copy link

@leilenah leilenah commented Nov 16, 2018

👏

@SuchismitaGoswami

This comment has been minimized.

Copy link

@SuchismitaGoswami SuchismitaGoswami commented Dec 14, 2018

FrogJmp Problem can be solved in O(1) time .

Solution:
function solution(X, Y, D) {
return Math.ceil(((Y-X)/D));
}

https://app.codility.com/demo/results/trainingQGSXX6-DX2/

@wzup

This comment has been minimized.

Copy link

@wzup wzup commented Apr 4, 2019

Why do you use % (division with remainder) for BinaryGap task?
https://app.codility.com/demo/results/trainingU2FQPQ-7Y4/

@tonifirnandes

This comment has been minimized.

Copy link

@tonifirnandes tonifirnandes commented Jul 21, 2019

Thank for this great work, so we can learn from each other for better/perfect solution. Anyway for this case i only got 90% using your code, maybe would you like to check it again or update it thanks.

https://codility.com/demo/results/trainingSREAJE-B4Q/

@Maravanna

This comment has been minimized.

Copy link

@Maravanna Maravanna commented Aug 28, 2019

Lesson 15 - CountTriangles
This code does not get 100% all of the time. (At least I couldn't get it, even once).
The code can be improved by moving the line
end = mid+1;
to before the second For, like
end = start + 2;
because you don't have to go all through the end part of the array again since once the array is ordered if (start + lastMid > end) then start + newMid will always be > end.
You just have to test the rest of it...
This will make the code 100%.
like with the modification - https://app.codility.com/demo/results/trainingPS6YB4-DQ3/

@boutahlilsoufiane

This comment has been minimized.

Copy link

@boutahlilsoufiane boutahlilsoufiane commented Sep 14, 2019

The solution of MaxProductOfThree is not correct 100%:
This is an example:
A[0] = -5
A[1] = 4
A[2] = 4
A[3] = 3
A[4] = -1
The program should return 48, but the result is 20

@Maravanna

This comment has been minimized.

Copy link

@Maravanna Maravanna commented Sep 14, 2019

The solution of MaxProductOfThree is not correct 100%:
This is an example:
A[0] = -5
A[1] = 4
A[2] = 4
A[3] = 3
A[4] = -1
The program should return 48, but the result is 20

Try this solution:
https://app.codility.com/demo/results/trainingESHJN9-ACJ/

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Sep 19, 2019

Thank you for the amazing work!

Lesson 6 - Distinct can be solved by using ES6.

function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
return (new Set(A)).size;
}

https://app.codility.com/demo/results/trainingRSRTET-8F2/

@arammkr

This comment has been minimized.

Copy link

@arammkr arammkr commented Sep 25, 2019

Hello, here is good solution for ArrayInversionCount, I'm using here merge sort to calculate inversion.

https://app.codility.com/demo/results/trainingYFRBTD-F58/

@lalkmim

This comment has been minimized.

Copy link
Owner Author

@lalkmim lalkmim commented Oct 18, 2019

Hey all, first I'm very glad this is helpful for someone other than me :), and sorry for not being very responsive, just noticed all github emails were going to a spam folder.

I put this together because I was planning to change jobs and thought it was a good idea to get myself "sharp" again on those types of exercises and couldn't really find a single place with all the solutions.

Some of the solutions might have gotten 100% on the tests but that doesn't mean they are a 100% correct for all scenarios (as some of you noticed), once I have some time I'll try to update the original doc to add the other solutions as well.

:)

@ignaciodediego

This comment has been minimized.

Copy link

@ignaciodediego ignaciodediego commented Mar 20, 2020

Thank you very much, it really helped me !

@sofinico

This comment has been minimized.

Copy link

@sofinico sofinico commented Mar 29, 2020

Thanks for sharing your solutions!

Here's another way of solving Lesson 2 - CyclicRotation with recursion:

function solution(A, K) {
    if (K === 0 || A === [])
        return A;
    
    const newFirstElement = A.pop();
    A.unshift(newFirstElement);

    return solution(A, K-1);
}

When testing just forgot the empty array case:
https://app.codility.com/demo/results/trainingMS7V6F-D9B/

@julian916

This comment has been minimized.

Copy link

@julian916 julian916 commented May 5, 2020

Here a more performant solution for Lesson 1 - BinaryGap
https://app.codility.com/demo/results/trainingBSDAJV-WZW/

@priyakishore921

This comment has been minimized.

Copy link

@priyakishore921 priyakishore921 commented May 17, 2020

Hi,
Thanks for sharing your solutions. They are very helpful.
I have another way of implementing Lesson 4 PermCheck
https://app.codility.com/demo/results/trainingEE6XV3-TRA/

@Jojr

This comment has been minimized.

Copy link

@Jojr Jojr commented Jun 20, 2020

Thanks for sharing!

@Knyazik01

This comment has been minimized.

Copy link

@Knyazik01 Knyazik01 commented Jul 14, 2020

Lesson 4 - Couting Elements
PermCheck ---- https://app.codility.com/demo/results/training8M2CGC-RSS/

This solution is faster :)

@deejoe79

This comment has been minimized.

Copy link

@deejoe79 deejoe79 commented Sep 5, 2020

Hi lalkmim,

I have another solution for the AbsDistinct (lesson 15). Take a look if you like it:

function solution(A) {
        // write your code in JavaScript (Node.js 8.9.4)
        let distinctValues = {};
	for (let i = 0; i < A.length; i++) {
		let prop = Math.abs(A[i]).toString();
		distinctValues[prop] = prop;
	}
	return Object.keys(distinctValues).length;
}
@zeeshanullah

This comment has been minimized.

Copy link

@zeeshanullah zeeshanullah commented Oct 23, 2020

Here is my solution to Lesson 2 (CyclicRotation) without using loops or recursion:
https://app.codility.com/demo/results/trainingEVYNBV-5FC/

@2sagarraut2

This comment has been minimized.

Copy link

@2sagarraut2 2sagarraut2 commented Jan 18, 2021

Hi, Can you please explain Lesson 4 MissingInteger?

@MustafaSarhan

This comment has been minimized.

Copy link

@MustafaSarhan MustafaSarhan commented May 18, 2021

Using JS filter you can distinct the array and get the length of it will be the number you looking for
return A.filter((v,i,s)=> s.indexOf(v) === i ).length;

@thekomx

This comment has been minimized.

Copy link

@thekomx thekomx commented May 30, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment