Skip to content

Instantly share code, notes, and snippets.

@lalkmim
Last active March 21, 2024 10:34
Show Gist options
  • Save lalkmim/e04845eb9d1c5936622a to your computer and use it in GitHub Desktop.
Save lalkmim/e04845eb9d1c5936622a to your computer and use it in GitHub Desktop.
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/
@leilenah
Copy link

👏

@SuchismitaGoswami
Copy link

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
Copy link

wzup commented Apr 4, 2019

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

@tonifirnandes
Copy link

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
Copy link

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
Copy link

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
Copy link

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/

Copy link

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
Copy link

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
Copy link
Author

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
Copy link

Thank you very much, it really helped me !

@sofinico
Copy link

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
Copy link

julian916 commented May 5, 2020

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

@priyakishore921
Copy link

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
Copy link

Jojr commented Jun 20, 2020

Thanks for sharing!

@Knyazik01
Copy link

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

This solution is faster :)

@deejoe79
Copy link

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
Copy link

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

@2sagarraut2
Copy link

Hi, Can you please explain Lesson 4 MissingInteger?

@MustafaSarhan
Copy link

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
Copy link

thekomx commented May 30, 2021

@lumayara
Copy link

Oi, vascaino! tudo bem? Leonardo, queria falar com vc! vc tem Linkedin?

@MackKaputo
Copy link

MackKaputo commented Oct 28, 2021

Lesson 3 - PermMissingElem can be solved using the fact that sum of consecutive elements from 1 to n equals n*(n+1)/2. Subtract all elements from the sum, you're left with the missing number

function solution(A) {

let maxNumber = A.length + 1 
let total_sum_assumed = maxNumber * (maxNumber + 1) / 2

for (let number of A){
    total_sum_assumed = total_sum_assumed - number
}

return total_sum_assumed 

}

@Knyazik01
Copy link

Lesson 5 - Prefix Sums
PassingCars

This solution is easer

https://app.codility.com/demo/results/trainingJTC3QW-P7C/

@flsouto
Copy link

flsouto commented Sep 24, 2022

PermCheck:

function solution(A){
    const mem = {}
    for(const v of A){
        if(v < 1 || v > A.length) return 0
        mem[v] = 1
    }
    return Object.keys(mem).length === A.length ? 1 : 0
}

@flsouto
Copy link

flsouto commented Sep 24, 2022

FrogRiverOne:

function solution(A){
    let mem = {};
    for(let i=0;i<A.length;i++){
        if(A[i] < X) mem[A[i]] = true
        if(A[i] === X && Object.keys(mem).length === X-1){
            return i
        }
    }
    return -1
}

@flsouto
Copy link

flsouto commented Sep 24, 2022

MaxCounters:

function solution(N,A){
    let counters = Array.from({length:N}).map(_=>0);
    for(const X of A){
        if(X >= 1 && X <= N){
            counters[X-1]++
        } else if(X === N+1){
            const greatest = Math.max(...counters)
            counters = counters.map(_ => greatest)
        }
    }
    return counters
}

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