Start learning free

LESSON 253 OF 289 · NESTED LOOPS

Employee of the Year V6 in TypeScript: 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: string[] = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"];
const productivities: number[] = [83, 133, 97, 150, 120];
const salaries: number[] = [135000, 335000, 210000, 250000, 180000];
const k: number = 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: boolean[] = 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: string[] = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"];
const productivities: number[] = [83, 133, 97, 150, 120];
const salaries: number[] = [135000, 335000, 210000, 250000, 180000];
const k: number = 3;

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

STEP 1 OF 9
    Ctrl + Enter to check

    TYPESCRIPT · NESTED LOOPS

    Employee Of The Year V6 in TypeScript, explained

    Problem overview

    The company gives a bonus to the k most productive employees. Three arrays describe the staff, and index i in all three belongs to the same person: names[i], productivities[i] and salaries[i]. The constant k says how many winners there are, and the code has to keep working when k changes.

    A winner's bonus is 15% of the salary, rounded down. The program prints one line per winner, best first, in the form name: $bonus. There is no sorting in this version: the search for the best employee is repeated k times, and each round skips the people who already won.

    For the starting data and k = 3, the three most productive employees are Alice Chen (150), Mary Jane (133) and Carlos Diaz (120):

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

    Bob Smith (97) and John Doe (83) are less productive than the three winners, so they get nothing.

    Approach: repeat the search, remembering the winners

    Finding the single best employee is a running maximum: scan everyone, keep the index of the best so far, replace it only on a strictly greater productivity. Doing that k times would find the same person every time, unless the winners are removed from the search.

    The program doesn't remove anyone. It marks them. A boolean array taken has one entry per employee, all false at first, and a winner's entry becomes true. Inside the search, a taken employee is skipped, so round 2 finds the best of the rest, round 3 the best of those still left, and so on.

    That gives two nested loops. The outer loop counts the rounds, once per winner. The inner loop scans all the employees in one round.

    The search starts each round with bestIndex equal to -1, which can't be a real index and so means nobody has been chosen yet. The test for a new best is "not taken, and either nobody is chosen yet or strictly more productive than the current best". The first untaken employee always passes through the -1 case, and later ones have to beat the current best.

    The strictness gives the tie rule for free: when two employees have the same productivity, the one listed first is reached first and keeps the lead.

    With the starting data, the rounds go like this:

    RoundBest among those not takenProductivity
    0Alice Chen150
    1Mary Jane133
    2Carlos Diaz120

    Step by step

    1. Create the flags. taken is a boolean[] built with new Array(names.length).fill(false): an array as long as the staff, with false in every slot.
    2. Write the outer loop. rank counts from 0 while it is below k, once per winner. The counter only counts rounds, and the loop body is one full search.
    3. Reset the best at the start of each round. Inside the outer loop, let bestIndex: number = -1. Declared here, it starts again with nobody chosen every round.
    4. Write the inner loop. i runs over every employee, because every round looks at everybody again.
    5. Test each employee. The if requires !taken[i] and either bestIndex === -1 or productivities[i] > productivities[bestIndex]. When it holds, set bestIndex to i.
    6. Check that someone was found after the inner loop: bestIndex !== -1. When k is larger than the number of employees, the last rounds find nobody and must print nothing.
    7. Mark the winner by setting taken[bestIndex] to true right away, because the next round reads it.
    8. Compute the bonus. A const named bonus: Math.floor(salaries[bestIndex] * 15 / 100). Multiplying first and dividing after keeps the arithmetic simple, and Math.floor drops any fraction.
    9. Print the winner as names[bestIndex], ": $" and bonus, joined with +. The name and the bonus both come from the winner's index.

    The solution in TypeScript

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

    Details worth knowing:

    • new Array(n).fill(false). new Array(5) alone creates an array of length 5 with empty slots, and fill(false) writes false into every one. The annotation boolean[] describes the result for the compiler and is erased at run time.
    • === and !==. They compare without converting types, which is the usual choice in TypeScript.
    • Short-circuit evaluation. && and || stop as soon as the result is known. In bestIndex === -1 || productivities[i] > productivities[bestIndex] the right side is never evaluated while bestIndex is -1.
    • The $ in the string. In ": $", an ordinary double-quoted string, the dollar sign is just a character. Only inside backtick template strings does $ followed by { start an expression.
    • A const inside the loop. bonus is created fresh on every pass of the if block, which is allowed because each pass has its own scope.

    Complexity

    Time: O(k * n). Each of the k rounds scans all n employees once, with constant work per employee. When k is close to n, that approaches O(n²). A sort would take O(n log n), but this lesson deliberately repeats the search.

    Space: O(n). The taken array has one entry per employee. Everything else is a few variables.

    Edge cases and common mistakes

    • Different values of k. With k = 1 only Alice Chen is printed. With k = 2 it is Alice Chen and Mary Jane. With k = 5 everybody is printed, adding Bob Smith ($31500) and John Doe ($20250).
    • k larger than the staff. With k = 7 the output is the same five lines as for k = 5. Rounds 6 and 7 find nobody, and the check on bestIndex keeps them silent.
    • Removing the check. Without the bestIndex !== -1 check and with k = 7, two extra lines appear: undefined: $NaN. An index of -1 reads undefined from an array, and the arithmetic on it gives NaN. There is no error, only wrong output.
    • k = 0. The outer loop never runs and the program prints nothing.
    • Ties. Suppose the productivities are [100, 150, 150, 90, 150]. The three employees with 150 win in list order: Mary Jane, Bob Smith, then Carlos Diaz. Writing >= instead of > reverses that order, printing Carlos Diaz first.
    • Leaving out the bestIndex === -1 case. If the test is only !taken[i] && productivities[i] > productivities[bestIndex], comparing against productivities[-1] (undefined) is always false, so no one is ever chosen and the program prints nothing.
    • Not marking the winner. Without setting taken[bestIndex] to true, every round picks the same employee again.

    Testing

    • The starting data with k = 1 prints Alice Chen: $37500.
    • With k = 2 it prints Alice Chen: $37500 and Mary Jane: $50250.
    • With k = 5 it adds Bob Smith: $31500 and John Doe: $20250 after Carlos Diaz.
    • With k = 7 the output equals k = 5.
    • With k = 0 there is no output.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free