Codility: NumberOfDiscIntersections Solution

Lesson 6 Sorting

Implementation

1function solution(A) {
2 let i = 0
3
4 // 1 means beginning, -1 mean ending
5 const points = A.map((a, i) => [
6 [i - a, 1],
7 [i + a, -1],
8 ])
9 .reduce((acc, el) => {
10 acc[i++] = el[0]
11 acc[i++] = el[1]
12 return acc
13 }, [])
14 .sort((a, b) => a[0] - b[0] || b[1] - a[1])
15
16 let intersections = (activeCircles = 0)
17 for (const [_, place] of points) {
18 if (place === 1) {
19 intersections += activeCircles
20 activeCircles += 1
21 } else {
22 activeCircles -= 1
23 }
24 if (intersections > 1e7) {
25 return -1
26 }
27 }
28
29 return intersections
30}

References

http://www.lucainvernizzi.net/blog/2014/11/21/codility-beta-challenge-number-of-disc-intersections/

Comments

Loading comments...

Tags

codility

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

Codility: MaxProductOfThree

Lesson 6 Sorting

Previous Post

Codility: Triangle

Lesson 6 Sorting

HoningJS

Search Posts