Codility: EquiLeader Solution
Lesson 8 LeaderApproach
Calculate 2 prefix leaders, for the array and its reversed
The result is number of equal pairs
Implementation
1function solution(A) {2 const getPrefixLeader = A => {3 let maxOcc, maxEl45 let prefixLeader = Array(A.length)6 maxOcc = maxEl = -Infinity7 A.reduce((acc, el, i) => {8 const occ = (acc[el] || 0) + 19 acc[el] = occ10 if (maxOcc < occ) {11 maxOcc = occ12 if (occ > Math.floor((i + 1) / 2)) {13 maxEl = el14 }15 }16 if (!(maxOcc > Math.floor((i + 1) / 2))) {17 maxEl = -118 }1920 prefixLeader[i] = maxEl21 return acc22 }, {})2324 return prefixLeader25 }2627 const prefixLeader = getPrefixLeader(A)28 const prefixLeaderReversed = getPrefixLeader(A.reverse()).reverse()2930 return prefixLeader.filter(31 (p, i) => p !== -1 && p === prefixLeaderReversed[i + 1]32 ).length33}
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.