Hackerrank: Frequency Queries Solution
Approach
Two hash tables
- one mapping element with its occurence
- one mapping occurrence with elements having that occurence
Implementation
1function freqQuery(queries) {2 const res = []3 const elOccMap = {}4 const occElMap = {}5 for (const [op, val] of queries) {6 switch (op) {7 case 1: {8 const curOcc = elOccMap[val]9 const newOcc = (curOcc || 0) + 11011 if (!occElMap[curOcc]) {12 occElMap[curOcc] = new Map()13 }14 occElMap[curOcc].delete(val)15 if (!occElMap[newOcc]) {16 occElMap[newOcc] = new Map()17 }18 occElMap[newOcc].set(val, true)1920 elOccMap[val] = newOcc21 break22 }23 case 2: {24 const curOcc = elOccMap[val]25 if (!curOcc) {26 break27 }28 const newOcc = curOcc - 12930 if (!occElMap[curOcc]) {31 occElMap[curOcc] = new Map()32 }33 occElMap[curOcc].delete(val)34 if (!occElMap[newOcc]) {35 occElMap[newOcc] = new Map()36 }37 occElMap[newOcc].set(val, true)3839 elOccMap[val] = newOcc40 break41 }42 case 3: {43 if (occElMap[val] && occElMap[val].size > 0) {44 res.push(1)45 } else {46 res.push(0)47 }48 break49 }50 }51 }52 return res53}
Comments
Loading comments...
Tags
hackerrank
hash table
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.
Previous Post
Codility: CountFactors
Lesson 10 Prime and Composite Numbers