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) + 1
10
11 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)
19
20 elOccMap[val] = newOcc
21 break
22 }
23 case 2: {
24 const curOcc = elOccMap[val]
25 if (!curOcc) {
26 break
27 }
28 const newOcc = curOcc - 1
29
30 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)
38
39 elOccMap[val] = newOcc
40 break
41 }
42 case 3: {
43 if (occElMap[val] && occElMap[val].size > 0) {
44 res.push(1)
45 } else {
46 res.push(0)
47 }
48 break
49 }
50 }
51 }
52 return res
53}

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.

Next Post

Hackerrank: Sherlock and the Valid String

Previous Post

Codility: CountFactors

Lesson 10 Prime and Composite Numbers

HoningJS

Search Posts