Why does Counter + extend cause TLE while manual counting works for [1701C]?"

Revision en2, by CipheredBytes, 2025-04-16 01:17:45

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.

Tags python, counter, tle

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en8 English CipheredBytes 2025-04-16 01:29:18 44 Tiny change: 'roach.\n\n' -> 'roach.\n\n\nCould it be due to hash table overhead ?\n'
en7 English CipheredBytes 2025-04-16 01:25:39 22
en6 English CipheredBytes 2025-04-16 01:20:57 9
en5 English CipheredBytes 2025-04-16 01:19:17 620
en4 English CipheredBytes 2025-04-16 01:18:50 8
en3 English CipheredBytes 2025-04-16 01:18:21 26 Tiny change: 'my recent Codeforces problem [problem:' -> 'my recent attempt with [problem:'
en2 English CipheredBytes 2025-04-16 01:17:45 117
en1 English CipheredBytes 2025-04-16 01:15:58 1679 Initial revision (published)