Given an array of size n and a number k, fin all elements that appear more than ” n/k ” times.
One Subscription, For Everything
The new cool way of learning and upskilling -
One Subscription access everything
Get Access to PrepInsta Prime
from FAANG/IITs/TOP MNC's
PrepInstaPrime
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others.
Login/Signup to comment
def appn(ar,n,k):
t = n//k
s = set(ar)
f=[]
for i in s:
if ar.count(i) > t:
f.append(i)
return f
n=int(input(‘Enter n:’))
print(‘Enter the ar elements:’)
ar=list(map(int,input().split()))
k=int(input(‘Enter k:’))
print(‘List of elements that appear more than n/k times are:’)
appn(ar,n,k)
# Python3 code to find elements whose
# frequency is more than n/k
def morethanNbyK(arr, n, k):
x = n // k
# unordered_map initialization
freq = {}
for i in range(n):
if arr[i] in freq:
freq[arr[i]] += 1
else:
freq[arr[i]] = 1
# Traversing the map
for i in freq:
# Checking if value of a key-value pair
# is greater than x (where x=n/k)
if (freq[i] > x):
# Print the key of whose value
# is greater than x
print(i)
# Driver code
if __name__ == ‘__main__’:
arr = [1, 1, 2, 2, 3, 5, 4, 2, 2, 3, 1, 1, 1]
n = len(arr)
k = 4
morethanNbyK(arr, n, k)
a=[1,2,3,3,2,1,3,2,7,7]
k=5
d=dict()
for i in a:
if i in d:
d[i]+=1
else:
d[i]=1
for key,value in d.items():
if value>(len(a)/k):
print(key)