[
counter
sort
]
BinarySearch 0311 Equal Piles
Problem statement
https://binarysearch.com/problems/Equal-Piles/
Solution
Use counter and imagine we have 2, 7, 3, 4
frequencies of elements 1, 2, 3, 4
. Then answer will be 2*0 + 7*1 + 3*2 + 4*3
.
Complexity
It is O(n log n)
for time and O(n)
for space.
Code
class Solution:
def solve(self, nums):
cnt = sorted(list(Counter(nums).items()), key = lambda x: x[0])
vals = [x for _, x in cnt]
return sum(i*x for i, x in enumerate(vals))