Start learning free

LESSON 186 OF 289 · LOOPING OVER ARRAY INDICES

Employee of the Year V5 in TypeScript: Top 2 Without Sorting

Practice Read the full explanation

Hand out bonuses to the top 2 most productive employees: the best one first, then the second best. You don't need any sorting. Find the best employee with the loop from v4, then find the best of the other employees with a second loop.

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];

Build:

Alice Chen: $37500
Mary Jane: $50250

Rules:

  • Index i in all three arrays refers to the same employee.
  • The best employee is the one with the highest productivity; the second best is the one with the highest productivity among all the other employees.
  • 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 two lines, the best employee first: name: $bonus.

Find the best employee first, exactly as in v4. Remember: strictly greater, so the first listed wins a tie.

For the second place, loop over all the indices and ignore the best one. The whole condition is if (i !== bestIndex && (secondIndex === -1 || productivities[i] > productivities[secondIndex])) {. "Nobody chosen yet" must also let an employee in.

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];

let bestIndex: number = 0;
for (let i: number = 1; i < names.length; i++) {
    if (productivities[i] > productivities[bestIndex]) {
        bestIndex = i;
    }
}
let secondIndex: number = -1;
for (let i: number = 0; i < names.length; i++) {
    if (i !== bestIndex && (secondIndex === -1 || productivities[i] > productivities[secondIndex])) {
        secondIndex = i;
    }
}
const bestBonus: number = Math.floor(salaries[bestIndex] * 15 / 100);
const secondBonus: number = Math.floor(salaries[secondIndex] * 15 / 100);
console.log(names[bestIndex] + ": $" + bestBonus);
console.log(names[secondIndex] + ": $" + secondBonus);

STEP 1 OF 10
    Ctrl + Enter to check

    TYPESCRIPT · LOOPING OVER ARRAY INDICES

    Employee Of The Year V5 in TypeScript, explained

    Problem overview

    The statement builds on the previous version's loop, which finds the one best employee. Version 5 awards bonuses to the top two: the most productive employee first, then the second most productive. The data is the same: names, productivities and salaries, where index i refers to the same employee in all three.

    The rules: the best employee has the highest productivity, the second best has the highest productivity among all the other employees, and ties go to the employee listed first. Each bonus is 15% of the salary, rounded down. Each output line has the form name: $bonus, best employee first:

    Alice Chen: $37500
    Mary Jane: $50250

    Alice Chen (150) is the best, and Mary Jane (133) is the best of everyone else. Sorting isn't required, so the lesson reuses the scanning idea from the previous version.

    Approach

    The first loop is the one from the last version. It leaves bestIndex pointing at the most productive employee. The second place is then the best among everyone except that employee, which is the same search with one person excluded.

    The second search keeps its own running best, secondIndex. It starts at -1, a value that is not a valid index, meaning that nobody has been chosen yet. A loop over all positions skips bestIndex and, for every other employee, takes them if no second place is chosen yet or if their productivity is strictly higher than the current second's.

    The special value matters. The second loop can't simply start with employee 0 as the candidate, because employee 0 might be the best employee, and the best can't take second place. Starting with "nobody" avoids the question. For the same reason, the second loop begins at 0 rather than 1: the best employee can be anywhere in the list, and every other position has to be considered.

    Step by step

    1. Create bestIndex at 0. It is a let because the loop may change it.
    2. Loop from 1 while i < names.length, visiting every other employee.
    3. Update on a strictly higher productivity. If productivities[i] > productivities[bestIndex], set bestIndex to i. After the loop it holds the winner, and a tie keeps the earlier employee.
    4. Create secondIndex at -1. No employee has that index, so it reads as "nobody yet".
    5. Loop from 0 while i < names.length. Every employee is a candidate except the best one, who is skipped inside the loop.
    6. Write the combined condition. The employee must not be the best (i !== bestIndex), and either secondIndex is still -1 or productivities[i] is strictly greater than productivities[secondIndex]. When all of that holds, set secondIndex to i.
    7. Compute bestBonus as Math.floor of the best employee's salary times 15 divided by 100.
    8. Compute secondBonus the same way from salaries[secondIndex].
    9. Print the best employee as the name, ": $" and the bonus.
    10. Print the second employee in the same form, on the next line.

    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];
    
    let bestIndex: number = 0;
    for (let i: number = 1; i < names.length; i++) {
        if (productivities[i] > productivities[bestIndex]) {
            bestIndex = i;
        }
    }
    let secondIndex: number = -1;
    for (let i: number = 0; i < names.length; i++) {
        if (i !== bestIndex && (secondIndex === -1 || productivities[i] > productivities[secondIndex])) {
            secondIndex = i;
        }
    }
    const bestBonus: number = Math.floor(salaries[bestIndex] * 15 / 100);
    const secondBonus: number = Math.floor(salaries[secondIndex] * 15 / 100);
    console.log(names[bestIndex] + ": $" + bestBonus);
    console.log(names[secondIndex] + ": $" + secondBonus);
    

    The details that matter:

    • Strict equality. !== and === compare without converting types. They are the usual choice in TypeScript, in place of != and ==.
    • Short-circuit order. In secondIndex === -1 || productivities[i] > productivities[secondIndex], the left side is checked first. When it is true, the right side is skipped, which is the case in which productivities[-1] would be meaningless: reading a negative index of an array gives undefined, and the comparison would be false.
    • The parentheses. && binds tighter than ||. Without the parentheses, the skip test would apply only to the first alternative, and the best employee could slip in through the second.
    • Two loops, two variables named i. Each let i belongs to its own loop, so reusing the name is fine.

    Complexity

    Time: O(n). There are two passes over the employees, each doing constant work per employee. Two passes are still linear.

    Space: O(1). The program keeps two indexes and two bonuses.

    Edge cases and common mistakes

    • Ties for the top. If two employees share the highest productivity, the earlier one is the best and the later one becomes second, because the second loop only skips bestIndex. With productivities [90, 90, 50, 10, 5], the output is John Doe: $20250 then Mary Jane: $50250: index 0 is best and index 1 second.
    • The best is the last employee. With [83, 97, 150, 10, 5], the output is Bob Smith: $31500 then Mary Jane: $50250.
    • Starting secondIndex at 0. With productivities [150, 133, 97, 10, 5] the best employee is index 0, and the loop can never replace the candidate at index 0, so both lines print John Doe: $20250. The -1 start gives the correct second line, Mary Jane: $50250.
    • Forgetting the skip. Without i !== bestIndex, the second loop finds the best employee again: with productivities [150, 133, 97, 10, 5] both lines print John Doe: $20250.

    Testing

    • The starter data prints Alice Chen: $37500 and Mary Jane: $50250.
    • Productivities [150, 133, 97, 10, 5] print John Doe: $20250 then Mary Jane: $50250.
    • Productivities [83, 97, 150, 10, 5] print Bob Smith: $31500 then Mary Jane: $50250.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free