# Hackerrank: Frequency Queries Solution

## Approach

Two hash tables

• one mapping element with its occurence
• one mapping occurrence with elements having that occurence

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}function 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) + 110
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] = newOcc21        break22      }23      case 2: {24        const curOcc = elOccMap[val]25        if (!curOcc) {26          break27        }28        const newOcc = curOcc - 129
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] = 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}```

hackerrank

hash table

## Next Post

Hackerrank: Sherlock and the Valid String

Jan 28, 2021

## Previous Post

Codility: CountFactors

Jan 26, 2021

Lesson 10 Prime and Composite Numbers

Search Posts