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

Task Assignment Implementation in Rust

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 Rust as in every other language.
  • ✓Vec<usize> for the index array, slice::sort_unstable_by_key for the keyed sort, and slice::sort_by_cached_key as the alternative when the key function itself is expensive enough to be worth computing once into a buffer rather than re-running it on every comparison.
  • ✓Sort an index Vec via sort_unstable_by_key(|&i| tasks[i]) rather than zipping tasks into (value, index) pairs; it avoids allocating n tuple wrappers, leaves tasks itself untouched for anyone else still holding a reference to it, and is the standard, well-worn pattern for exactly this "sort by a derived key, keep the original" shape.
  • ✓The Rust trap: hi is a usize, and the loop decrements it every iteration while walking inward: hi -= 1 when hi is already 0 underflows.
  • ✓sort_unstable_by_key re-reads tasks[i] on every comparison inside the closure, which is fine since the key here is a single array lookup.

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 Rust: what you actually reach for

Vec<usize> for the index array, slice::sort_unstable_by_key for the keyed sort, and slice::sort_by_cached_key as the alternative when the key function itself is expensive enough to be worth computing once into a buffer rather than re-running it on every comparison.

Rust implementation

Sort an index Vec via sort_unstable_by_key(|&i| tasks[i]) rather than zipping tasks into (value, index) pairs; it avoids allocating n tuple wrappers, leaves tasks itself untouched for anyone else still holding a reference to it, and is the standard, well-worn pattern for exactly this "sort by a derived key, keep the original" shape.
rust
fn task_assignment(k: usize, tasks: &[i32]) -> Vec<(usize, usize)> {
    let mut indices: Vec<usize> = (0..tasks.len()).collect();
    indices.sort_unstable_by_key(|&i| tasks[i]);   // sorts the INDEX vec, tasks itself is untouched

    let mut pairs = Vec::with_capacity(k);
    let mut lo = 0usize;
    let mut hi = indices.len() - 1;
    for _ in 0..k {
        pairs.push((indices[lo], indices[hi]));
        lo += 1;
        // hi is unsigned: guard before subtracting or the last iteration underflows
        if hi > 0 {
            hi -= 1;
        }
    }
    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 Rust-specific trap

hi is a usize, and the loop decrements it every iteration while walking inward: hi -= 1 when hi is already 0 underflows. Debug builds panic on that overflow; a release build compiled with the default overflow-checks = false wraps silently to usize::MAX, and the next indices[hi] then panics with an out-of-bounds index instead of the real error.

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

sort_unstable_by_key re-reads tasks[i] on every comparison inside the closure, which is fine since the key here is a single array lookup. sort_by_cached_key exists for when the key computation itself is expensive enough to be worth precomputing once into an auxiliary O(n) buffer, and reaching for it here would be pure overhead for a key this cheap. 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 Rust, 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 Rust, demonstrate proficiency with ownership system and pattern matching to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Rust code that is both correct and maintainable.

Frequently Asked Questions

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

Vec<usize> for the index array, slice::sort_unstable_by_key for the keyed sort, and slice::sort_by_cached_key as the alternative when the key function itself is expensive enough to be worth computing once into a buffer rather than re-running it on every comparison.

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

hi is a usize, and the loop decrements it every iteration while walking inward: hi -= 1 when hi is already 0 underflows. Debug builds panic on that overflow; a release build compiled with the default overflow-checks = false wraps silently to usize::MAX, and the next indices[hi] then panics with an out-of-bounds index instead of the real error.

How does Task Assignment actually perform in Rust?

sort_unstable_by_key re-reads tasks[i] on every comparison inside the closure, which is fine since the key here is a single array lookup. sort_by_cached_key exists for when the key computation itself is expensive enough to be worth precomputing once into an auxiliary O(n) buffer, and reaching for it here would be pure overhead for a key this cheap. 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

If you are a student, see what GitHub Copilot offers students for free 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.