Home > Mobile >  Return Missing balancing numbers
Return Missing balancing numbers

Time:02-08

A balanced array would be an array in which each element appears the same number of times.

Given an array with n elements: return a dictionary with the key as the element and the value as the count of elements needed to balance the given array

Examples

elements = ["a", "b", "abc", "c", "a"]

Expected output: {"b":1, "abc":1, "c":1}

Because there are 2 a, we need 1 more of b, abc, c

Hope that helps

CodePudding user response:

You can use the Counter to calculate frequencies and then get required frequencies by iterating through it -

from collections import Counter
elements = ["a", "b", "abc", "c", "a"]
counts = Counter(elements)
max_freq = max(counts.values())    # 2 in this case
ans = {k: max_freq - v for k, v in counts.items() if v < max_freq}
print(ans)

outputs -

{'b': 1, 'abc': 1, 'c': 1}

CodePudding user response:

This isn't homework but a Meta Data Engineer interview prep question ;)

This is my solution without using Counter

lst = ["a", "b", "abc", "c", "a"]    
tuples = [(i, lst.count(i)) for i in lst]
tuples.sort(key=lambda x: -x[1])
max_value = tuples[0]
      
{k: max_value[1] - v for k,v in tuples if v < max_value[1]}
  •  Tags:  
  • Related