Start learning free

LESSON 256 OF 293 · NESTED LOOPS

Employee of the Year V6 in Rust: Top K Without Sorting

Practice Read the full explanation

Generalize the previous version: give bonuses to the top K most productive employees, where k is given as a variable. Still no sorting: repeat the search for the best employee k times, and remember who already won so nobody wins twice.

You start with:

let names = vec!["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"];
let productivities = vec![83, 133, 97, 150, 120];
let salaries = vec![135000, 335000, 210000, 250000, 180000];
let k = 3;

Build:

Alice Chen: $37500
Mary Jane: $50250
Carlos Diaz: $27000

Rules:

  • Index i in all three vectors refers to the same employee.
  • Round 1 finds the employee with the highest productivity, round 2 the best among the employees who have not won yet, and so on, for k rounds.
  • If two employees have the same productivity, the one listed first wins.
  • Each bonus is 15% of the salary, rounded down (with integer division).
  • Print one line per winner, best first: name: $bonus.
  • If k is larger than the number of employees, everybody wins once and you print one line per employee: when nobody is left, a round prints nothing.
  • Your code must keep working when k changes to 1, 2, 5 or 7.

Use a list of booleans: let mut taken = vec![false; names.len()];. A round finds the best employee among those who are not taken yet, then marks that employee as taken.

The outer loop runs k times and the inner loop is the search from v4 with one more condition: if !taken[i] && (bestIndex == names.len() || productivities[i] > productivities[bestIndex]) {. If nobody is found in a round, skip the rest of that round.

let names = vec!["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"];
let productivities = vec![83, 133, 97, 150, 120];
let salaries = vec![135000, 335000, 210000, 250000, 180000];
let k = 3;

let mut taken = vec![false; names.len()];
for _rank in 0..k {
    let mut bestIndex = names.len();
    for i in 0..names.len() {
        if !taken[i] && (bestIndex == names.len() || productivities[i] > productivities[bestIndex]) {
            bestIndex = i;
        }
    }
    if bestIndex != names.len() {
        taken[bestIndex] = true;
        let bonus = salaries[bestIndex] * 15 / 100;
        println!("{}: ${}", names[bestIndex], bonus);
    }
}

STEP 1 OF 9
    Ctrl + Enter to check

    RUST · NESTED LOOPS

    Employee Of The Year V6 in Rust, explained

    Problem overview

    A company gives bonuses to its k most productive employees. Three vectors describe the staff: names, productivities and salaries. Index i in all three refers to the same person. The starting data has five employees and k = 3.

    The program prints one line per winner, best first, in the form name: $bonus. A bonus is 15% of the salary, rounded down by integer division. For the starting data:

    Alice Chen: $37500
    Mary Jane: $50250
    Carlos Diaz: $27000
    

    Alice has the highest productivity, 150, and a salary of 250000, which gives 37500. Mary is next with 133, and Carlos third with 120. If two employees have the same productivity, the one listed first wins. If k is larger than the number of employees, everybody wins once and nothing extra is printed. The program must keep working when k changes.

    Approach: repeat the search, remember the winners

    Sorting is not allowed here. Instead, the program repeats a plain search for the best employee k times. A search by itself would find Alice every time, so it needs a way to skip people who already won. A vector of flags, taken, has one false for each employee, and a winner's flag is switched to true. Every later round ignores flagged employees, so round 2 finds the best among those who remain.

    Each round needs a way to say "nobody found yet". Rust indexes are unsigned, so the usual -1 is unavailable. The program uses names.len() instead: it is one past the last valid index, so no real employee can have that value.

    The test for a new best employee has two parts. The employee must not be taken, and either nobody has been chosen in this round yet, or this employee's productivity is strictly greater than the current best's. Strictly greater is what implements the tie rule: a later employee with equal productivity doesn't replace an earlier one.

    After the search, the program checks that it found someone. When k is larger than the staff, the late rounds find nobody and must print nothing.

    Step by step

    1. Create taken with vec![false; names.len()]: one flag per employee, all false because nobody has won yet.
    2. Start the rounds with for _rank in 0..k. The counter only counts rounds, and the leading underscore tells Rust it is never read.
    3. Create bestIndex inside the round with the value names.len(), meaning nobody is chosen. Creating it inside the loop resets it every round.
    4. Open the inner loop over every position i in 0..names.len(). Each round looks at everybody again.
    5. Test each employee. The if requires !taken[i] and either bestIndex == names.len() or a strictly higher productivity than bestIndex. When it holds, bestIndex becomes i.
    6. Check that someone was found after the inner loop: bestIndex != names.len(). Otherwise the code below would index a vector with a value that is not an employee.
    7. Mark the winner by setting taken[bestIndex] to true, immediately, because the next round reads it.
    8. Compute bonus as the winner's salary times 15 divided by 100.
    9. Print the line with the name at bestIndex and the bonus.

    The solution in Rust

    let names = vec!["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"];
    let productivities = vec![83, 133, 97, 150, 120];
    let salaries = vec![135000, 335000, 210000, 250000, 180000];
    let k = 3;
    
    let mut taken = vec![false; names.len()];
    for _rank in 0..k {
        let mut bestIndex = names.len();
        for i in 0..names.len() {
            if !taken[i] && (bestIndex == names.len() || productivities[i] > productivities[bestIndex]) {
                bestIndex = i;
            }
        }
        if bestIndex != names.len() {
            taken[bestIndex] = true;
            let bonus = salaries[bestIndex] * 15 / 100;
            println!("{}: ${}", names[bestIndex], bonus);
        }
    }
    

    Rust details worth knowing:

    • Short-circuit evaluation. || and && stop as soon as the answer is known. When bestIndex == names.len() is true, the right side, productivities[bestIndex], is never evaluated. That matters, because evaluating it would index one past the end and panic.
    • Precedence. && binds tighter than ||, so the parentheses are needed to make !taken[i] apply to both alternatives.
    • $ in the format string. The $ before the second {} is an ordinary character in println!, so it prints as a dollar sign.
    • Naming style. Rust convention would call the variable best_index, and the compiler warns about the camel-case bestIndex. It is a warning only, and the output is correct.
    • Integer arithmetic. The salaries are i32 values, so salary * 15 / 100 multiplies first and divides second. For a salary of 135000 it gives 20250, and for a salary of 999 it gives 149, with the fraction dropped.

    Complexity

    Time: O(k * n) for n employees, because each of the k rounds scans all n of them. With k equal to n this becomes O(n²), which is why sorting would be better for a large staff. Space: O(n) for the taken flags.

    Edge cases and common mistakes

    • Different values of k. With k = 1 the output is only Alice. With k = 2 it is Alice and Mary. With k = 0 nothing is printed.
    • k larger than the staff. With k = 5 the output is Alice Chen ($37500), Mary Jane ($50250), Carlos Diaz ($27000), Bob Smith ($31500) and John Doe ($20250). With k = 7 it is the same five lines: the last two rounds find nobody and print nothing.
    • Ties. For employees A, B and C with productivities 100, 100 and 90, and salaries 1000, 2000 and 3000, k = 2 gives A: $150 and then B: $300. A, listed first, wins the tie. With >= in the comparison, B would replace A.
    • Forgetting to mark the winner. If taken[bestIndex] is never set, every round finds Alice again and prints her k times.
    • Creating bestIndex outside the rounds. It would keep the previous winner, and later rounds would compare against someone already taken.
    • Skipping the "found" check. When k exceeds the staff, names[bestIndex] with bestIndex equal to the length panics with index out of bounds.

    Testing

    • The starting data with k = 3 prints Alice Chen $37500, Mary Jane $50250 and Carlos Diaz $27000.
    • k = 1 prints Alice Chen: $37500 only.
    • k = 5 and k = 7 print all five employees in order of productivity: Alice, Mary, Carlos, Bob, John.
    • k = 0 prints nothing.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free