Start learning free

LESSON 250 OF 671 · NESTED LOOPS

Employee of the Year V6 in JavaScript: Top K with Nested Loops

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:

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

Build:

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

Rules:

  • Index i in all three arrays 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 Math.floor).
  • 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: const taken = new Array(names.length).fill(false);. 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 === -1 || productivities[i] > productivities[bestIndex])) {. If nobody is found in a round, skip the rest of that round.

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

const taken = new Array(names.length).fill(false);
for (let rank = 0; rank < k; rank++) {
    let bestIndex = -1;
    for (let i = 0; i < names.length; i++) {
        if (!taken[i] && (bestIndex === -1 || productivities[i] > productivities[bestIndex])) {
            bestIndex = i;
        }
    }
    if (bestIndex !== -1) {
        taken[bestIndex] = true;
        const bonus = Math.floor(salaries[bestIndex] * 15 / 100);
        console.log(names[bestIndex] + ": $" + bonus);
    }
}

STEP 1 OF 9
    Ctrl + Enter to check

    JAVASCRIPT · NESTED LOOPS

    Employee Of The Year V6 in JavaScript, explained

    Problem overview

    Version 6 generalises the "best employee" search: instead of one winner, the top k most productive employees each get a bonus, where k is a variable. There is still no sorting. The program repeats the search for the best employee k times, and remembers who has already won so nobody wins twice.

    The three arrays line up by index: names[i], productivities[i] and salaries[i] describe the same employee. The bonus is 15% of the salary, rounded down. With k = 3 the output is:

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

    Alice Chen has the highest productivity (150), then Mary Jane (133), then Carlos Diaz (120). If two employees tie, the one listed first wins. If k is larger than the number of employees, everybody wins once and no extra lines are printed.

    Approach: repeat the search, skipping earlier winners

    Finding one maximum means scanning the list while keeping the position of the best employee so far. Doing that three times would find Alice Chen three times, so each round needs to ignore the people who already won. The lesson keeps an array taken with one boolean per employee: taken[i] is true once employee i has won.

    That gives two nested loops. The outer loop counts rounds, one per winner. The inner loop is the search over all employees, skipping the taken ones. When the inner loop finishes, bestIndex holds the winner of the round, who is then marked as taken, so the next round finds the runner-up.

    The cost is k scans of n employees, which is O(k * n) time with one extra array of n booleans. Sorting once would be faster for a large k, but this lesson practises nested loops, and for a small k the repeated scan is simple and fast.

    Step by step

    1. Create taken. new Array(names.length) makes an empty array that long, and fill(false) puts false in every slot. Nobody has won yet.
    2. Write the outer loop. rank goes from 0 while rank < k: one pass per winner. The counter only counts rounds.
    3. Create bestIndex inside the round with let, starting at -1. No employee has index -1, so it means nobody is chosen yet. Because it is created inside the outer loop, every round starts afresh.
    4. Write the inner loop over every position i of names. Each round looks at everybody again.
    5. Write the condition. An employee becomes the round's best when they have not won (!taken[i]) and either nobody is chosen yet (bestIndex === -1) or their productivity is strictly greater than the current best's. Then bestIndex becomes i. "Strictly greater" is what makes ties go to the employee listed first.
    6. Check that someone was found. After the inner loop, bestIndex !== -1. If k exceeds the number of employees, the last rounds find nobody and must print nothing.
    7. Mark the winner by setting taken[bestIndex] to true, immediately, because the next round reads it.
    8. Compute the bonus in a const: Math.floor(salaries[bestIndex] * 15 / 100).
    9. Print the winner as name: $bonus.

    The solution in JavaScript

    const names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"];
    const productivities = [83, 133, 97, 150, 120];
    const salaries = [135000, 335000, 210000, 250000, 180000];
    const k = 3;
    
    const taken = new Array(names.length).fill(false);
    for (let rank = 0; rank < k; rank++) {
        let bestIndex = -1;
        for (let i = 0; i < names.length; i++) {
            if (!taken[i] && (bestIndex === -1 || productivities[i] > productivities[bestIndex])) {
                bestIndex = i;
            }
        }
        if (bestIndex !== -1) {
            taken[bestIndex] = true;
            const bonus = Math.floor(salaries[bestIndex] * 15 / 100);
            console.log(names[bestIndex] + ": $" + bonus);
        }
    }
    

    The details worth a closer look:

    • new Array(n).fill(false). new Array(3) alone is a sparse array with three empty slots, and reading a slot gives undefined. fill(false) makes every slot a real false.
    • Short-circuit evaluation. In !taken[i] && (...), the parenthesised test only runs for employees who are still available. Inside it, bestIndex === -1 || comes first, so productivities[bestIndex] is never read while bestIndex is -1.
    • The parentheses. && binds tighter than ||. Without the parentheses, the !taken[i] test would apply only to the first of the two alternatives.
    • $ in a string. In an ordinary quoted string "$" is just a character. Joining with + turns the number into text.
    • Rounding. salaries[bestIndex] * 15 / 100 multiplies before it divides, and Math.floor drops the cents. Alice's 250000 gives exactly 37500.

    Edge cases and common mistakes

    • k larger than the number of employees. With k = 5 every employee wins once and the output has five lines. With k = 7 the output is the same five lines. The rounds after the fifth find nobody, bestIndex stays -1, and the check skips them. Without the check, salaries[-1] would be undefined, and the program would print undefined: $NaN.
    • Ties. For names ["A", "B", "C"] with productivities [100, 100, 90] and salaries [1001, 2000, 333], A wins the first round and B the second, because the comparison is strict and A is listed first.
    • Rounding. A salary of 1001 gives 150.15, and 333 gives 49.95. The lesson's rule rounds down, so the bonuses are 150 and 49.
    • Forgetting to mark the winner. Without taken[bestIndex] = true, every round would pick Alice Chen again.
    • Declaring bestIndex outside the outer loop. It would keep the previous winner's index into the next round, and the === -1 test would never fire again.
    • k = 0. The outer loop doesn't run and nothing is printed.

    Testing

    • k = 3 prints Alice Chen ($37500), Mary Jane ($50250) and Carlos Diaz ($27000).
    • k = 1 prints only Alice Chen: $37500.
    • k = 2 adds Mary Jane: $50250.
    • k = 5 and k = 7 print the same five lines: Alice Chen $37500, Mary Jane $50250, Carlos Diaz $27000, Bob Smith $31500 and John Doe $20250.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free