Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Task Assignment Implementation in Python

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Task Assignment runs in O(n log n) time and O(n) space, in Python as in every other language.
  • ✓list, enumerate, and sorted(key=...) are the whole toolkit here, no special container is needed.
  • ✓Reach for enumerate() plus a key= lambda instead of tracking indices in a parallel list: sorted(enumerate(tasks), key=lambda p: p[1]) keeps each duration bolted to its original index through the sort, and is the idiom Python reviewers expect over building index arrays by hand.
  • ✓The Python trap: sorted(enumerate(tasks)) without key= sorts by the whole (index, value) tuple, comparing index first, and since index is already 0..n-1, that sort is a no-op that returns exactly the input order.
  • ✓enumerate() itself is a lazy generator, no list behind it. sorted() over it does materialize a real O(n) list of (index, value) tuples, and that list of small heap-allocated tuples is exactly the O(n) space this algorithm spends; sorting the bare durations alone, if indices weren't needed, would be measurably cheaper per element.

What Task Assignment actually is

Task Assignment: you have twice as many tasks as workers, every worker must complete exactly two of them one after another, and you want to choose the pairing that minimizes the heaviest worker's total, the largest single sum any one worker ends up carrying, since that worker is the last one to finish. The greedy proof is a short exchange argument: sort every task by how long it takes, then pair the shortest remaining task with the longest remaining task and work inward. Every language below implements that one idea, so the algorithm is identical everywhere. What differs is how each language keeps a task's ORIGINAL position attached to it once you've sorted by duration, because the answer has to name which task indices go to which worker, not just which durations. Some languages sort (duration, index) pairs directly and destructure them back apart; some sort a bare array of indices and look values up through it on every comparison; one gets to skip almost all of that bookkeeping because its standard library already knows how to walk two ends of a collection toward each other. That bookkeeping, and what silently breaks when you get it slightly wrong, is the real subject of this page.

Task Assignment in Python: what you actually reach for

list, enumerate, and sorted(key=...) are the whole toolkit here, no special container is needed. operator.itemgetter(1) is the idiomatic key= for the enumerate() pairs when you want the extraction done in C rather than through a Python-level lambda.

Python implementation

Reach for enumerate() plus a key= lambda instead of tracking indices in a parallel list: sorted(enumerate(tasks), key=lambda p: p[1]) keeps each duration bolted to its original index through the sort, and is the idiom Python reviewers expect over building index arrays by hand.
python
def task_assignment(k: int, tasks: list[int]) -> list[tuple[int, int]]:
    # decorate-sort-undecorate: keep the original index attached to each duration
    ranked = sorted(enumerate(tasks), key=lambda pair: pair[1])

    pairs: list[tuple[int, int]] = []
    lo, hi = 0, len(ranked) - 1
    for _ in range(k):
        shortest_idx, _ = ranked[lo]
        longest_idx, _ = ranked[hi]
        pairs.append((shortest_idx, longest_idx))
        lo += 1
        hi -= 1
    return pairs

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Python-specific trap

sorted(enumerate(tasks)) without key= sorts by the whole (index, value) tuple, comparing index first, and since index is already 0..n-1, that sort is a no-op that returns exactly the input order. No exception, just a pairing that quietly ignores every duration.

Performance in Python, beyond the O(n log n)

enumerate() itself is a lazy generator, no list behind it. sorted() over it does materialize a real O(n) list of (index, value) tuples, and that list of small heap-allocated tuples is exactly the O(n) space this algorithm spends; sorting the bare durations alone, if indices weren't needed, would be measurably cheaper per element. The asymptotic cost is the same in every language, O(n log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Task Assignment between languages.

Real-World Applications

Task Assignment applies wherever its problem shape appears in your own code. In Python, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Task Assignment helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Task Assignment appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Task Assignment over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Task Assignment to build pattern recognition. In Python, demonstrate proficiency with list comprehensions and generator expressions to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Python code that is both correct and maintainable.

Frequently Asked Questions

Which Python type or library should I use for Task Assignment?

list, enumerate, and sorted(key=...) are the whole toolkit here, no special container is needed. operator.itemgetter(1) is the idiomatic key= for the enumerate() pairs when you want the extraction done in C rather than through a Python-level lambda.

What is the most common Python mistake when implementing Task Assignment?

sorted(enumerate(tasks)) without key= sorts by the whole (index, value) tuple, comparing index first, and since index is already 0..n-1, that sort is a no-op that returns exactly the input order. No exception, just a pairing that quietly ignores every duration.

How does Task Assignment actually perform in Python?

enumerate() itself is a lazy generator, no list behind it. sorted() over it does materialize a real O(n) list of (index, value) tuples, and that list of small heap-allocated tuples is exactly the O(n) space this algorithm spends; sorting the bare durations alone, if indices weren't needed, would be measurably cheaper per element. Time complexity is O(n log n) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Before paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.