Skip to content

Instantly share code, notes, and snippets.

@sharno
Last active December 2, 2022 09:55
Show Gist options
  • Save sharno/9562e8f99761f41817daf522279635cb to your computer and use it in GitHub Desktop.
Save sharno/9562e8f99761f41817daf522279635cb to your computer and use it in GitHub Desktop.
hackerearth: Sum as per frequency
'''
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''
# Write your code here
N = int(input())
xs = input()
xs = [int(x) for x in xs.split()]
Q = int(input())
qs = []
for i in range(Q):
q = input()
[l, r] = q.split()
qs.append((int(l), int(r)))
# number to frequency dictionary
nf = {}
for x in xs:
f = nf.get(x, 0)
nf[x] = f + 1
# frequency to sum of numbers of the same frequency dictionary
fn = {}
for k,v in nf.items():
ns = fn.get(v, 0)
fn[v] = ns + k*v
# list with its index as the frequency and the value as the sum of numbers of this frequency
fs = []
for i in range(max(fn.keys()) + 1):
fs.append(fn.get(i, 0))
# solution
for (l, r) in qs:
print(sum(fs[l:r+1]))
@Venkat-Sai-S
Copy link

``s index as the frequency and the value a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment