Skip to content
Advertisement

Hacker Rank Frequency Queries [closed]

I am doing the Hacker Rank Frequency Queries question and all my test cases pass but one for Time limit exceeded. What can I do to make my program more efficient.

JavaScript

Advertisement

Answer

The time complexity of boolean containsValue(Object value) of class HashMap<K,V> is O(n). If in case 3, you can do a constant time look up – O(1), your code will be quite efficient.

According to the constraints mentioned in the problem statement:

  • Maximum number of queries:

    1 <= q <= 10^5

  • Maximum possible value of x, y and z:

    1 <= x, y, z <= 10^9

In order to check if any integer is present in your data structure whose frequency is exactly z in O(1), you can use an simple array.

If there is an element e in your array at an index z, then it will denote that there are e elements in your data structure with frequency z. The index of your array denotes frequency and the value at that index denotes the number of elements in your data structure with that frequency. You can call this array as nestedFrequency since it stores the frequency of frequencies. The size of the array will be 100001. Since the maximum number of possible queries are 100000, there can be no element whose frequency is greater than 100000.

Pseudocode:

JavaScript

I hope I have helped you. Do comment for any further problems.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement