In my recent Codeforces problem 1701C - Schedule Management, I encountered a situation where I need to count the frequency of tasks assigned to machines and then process this information in a certain way. I implemented two different approaches, one using a manual approach with arr[x-1] and the other using Counter to get task frequencies.
Here is a brief explanation of both approaches:
First Approach (Works Fine): 315769984
arr = [0] * n
for x in li():
arr[x - 1] += 1
arr.sort(reverse=True)
Explanation: I initialize an array arr with zeros, where each index represents a machine (0-indexed). For each task in li(), I increment the corresponding machine’s count in arr. After that, I sort the array in descending order to get the task distribution from highest to lowest.
Second Approach (Causes Time Limit Exceeded): 315770224
from collections import Counter
arr = list(sorted(Counter(li()).values(), reverse=True))
arr.extend([0] * (n - len(arr)))
Explanation: Here, I use the Counter to directly count the occurrences of each task, which gives a dictionary of task counts. I then take the values (the frequencies), sort them in descending order, and pad the array with zeros so that its length matches n. The resulting arr is then processed in the same way as the first approach.
Issue: This approach causes a Time Limit Exceeded (TLE) error, even though it seems like a more optimized approach.



