Start learning free

LESSON 186 OF 291 · LOOPING OVER ARRAY INDICES

Employee of the Year V5 in Scala: 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:

        val names = Array("John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz")
        val productivities = Array(83, 133, 97, 150, 120)
        val salaries = Array(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 integer division).
  • 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.

        val names = Array("John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz")
        val productivities = Array(83, 133, 97, 150, 120)
        val salaries = Array(135000, 335000, 210000, 250000, 180000)

        var bestIndex = 0
        for (i <- 1 until names.size) {
            if (productivities(i) > productivities(bestIndex)) {
                bestIndex = i
            }
        }
        var secondIndex = -1
        for (i <- 0 until names.size) {
            if (i != bestIndex && (secondIndex == -1 || productivities(i) > productivities(secondIndex))) {
                secondIndex = i
            }
        }
        val bestBonus = salaries(bestIndex) * 15 / 100
        val secondBonus = salaries(secondIndex) * 15 / 100
        println(names(bestIndex) + ": $" + bestBonus)
        println(names(secondIndex) + ": $" + secondBonus)

STEP 1 OF 10
    Ctrl + Enter to check

    SCALA · LOOPING OVER ARRAY INDICES

    Employee Of The Year V5 in Scala, explained

    Problem overview

    This version pays bonuses to the two most productive employees, the best first and the second best after. The data is the same five employees in three parallel arrays: names, productivities and salaries, where index i describes one person in all three. Each bonus is 15% of the salary, rounded down, and ties go to the employee listed first. The output has one line per winner, in the form name: $bonus.

    Alice Chen has the highest productivity (150) and Mary Jane the next (133). Their bonuses are 250000 * 15 / 100 = 37500 and 335000 * 15 / 100 = 50250:

    Alice Chen: $37500
    Mary Jane: $50250
    

    The previous version found the single best employee with a loop. This one reuses that loop and adds a second one.

    Approach: find the best, then the best of the rest

    The task needs no sorting. The second best employee is simply the most productive one among everybody except the best. So the program works in two passes:

    1. The first pass is the loop from the last version. It leaves the best employee's position in bestIndex.
    2. The second pass scans every employee again, skips bestIndex, and keeps the position of the best of the rest in secondIndex.

    The second pass has a small problem the first one didn't. The first pass can start with employee 0 as a candidate, but in the second pass employee 0 might be the overall winner and so not allowed. The program can't know a safe starting candidate in advance. The fix is a marker value: secondIndex starts at -1, which is not a position in any array and so means "nobody chosen yet". The first employee who isn't the winner is accepted automatically, and from then on a strictly higher productivity is needed to replace them.

    Because the comparisons are strict, ties still go to the earlier employee in both passes.

    Step by step

    1. Create bestIndex as a var at 0, assuming employee 0 is the best so far.
    2. Loop over 1 until names.size. Employee 0 is the starting best, so the scan starts at 1.
    3. Update on a strictly higher productivity. If productivities(i) beats productivities(bestIndex), set bestIndex to i.
    4. Create secondIndex as a var at -1, meaning nobody is chosen yet.
    5. Write a second loop over 0 until names.size. This one starts at 0, since the winner can sit anywhere in the list and is skipped inside the loop instead.
    6. Write the condition for becoming second best. The employee must not be the winner (i != bestIndex), and either nobody is chosen yet (secondIndex == -1) or the productivity is strictly higher than that of secondIndex. Then set secondIndex to i.
    7. Compute bestBonus from salaries(bestIndex).
    8. Compute secondBonus the same way from salaries(secondIndex).
    9. Print the best employee as the name, a colon, a space, a dollar sign and the bonus.
    10. Print the second best in the same form on the next line.

    The solution in Scala

            val names = Array("John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz")
            val productivities = Array(83, 133, 97, 150, 120)
            val salaries = Array(135000, 335000, 210000, 250000, 180000)
    
            var bestIndex = 0
            for (i <- 1 until names.size) {
                if (productivities(i) > productivities(bestIndex)) {
                    bestIndex = i
                }
            }
            var secondIndex = -1
            for (i <- 0 until names.size) {
                if (i != bestIndex && (secondIndex == -1 || productivities(i) > productivities(secondIndex))) {
                    secondIndex = i
                }
            }
            val bestBonus = salaries(bestIndex) * 15 / 100
            val secondBonus = salaries(secondIndex) * 15 / 100
            println(names(bestIndex) + ": $" + bestBonus)
            println(names(secondIndex) + ": $" + secondBonus)
    

    Scala details worth knowing:

    • Short-circuit operators. In secondIndex == -1 || productivities(i) > productivities(secondIndex), the right side is evaluated only when the left side is false. This matters: when secondIndex is -1, the right side would read productivities(-1) and throw an exception. The || test for -1 protects it.
    • Parentheses around the ||. && binds tighter than ||, so without the parentheses the condition would mean something different: "not the winner and nobody chosen yet", or "higher than the current second". The winner could then be picked as second.
    • Arrays use parentheses for reading elements, and until excludes its end, so 0 until names.size visits indexes 0 to 4.
    • The Int bonus. Multiplying by 15 before dividing by 100 keeps the rounding down correct, and the values stay far below the 32-bit limit.

    Following the program

    The first loop ends with bestIndex equal to 3, Alice Chen. In the second loop, with the starter productivities 83, 133, 97, 150 and 120:

    • Index 0 is not the winner and nobody is chosen yet, so secondIndex becomes 0 (83).
    • Index 1 has 133, higher than 83, so secondIndex becomes 1.
    • Index 2 has 97, which doesn't beat 133.
    • Index 3 is the winner and is skipped.
    • Index 4 has 120, which doesn't beat 133.

    So Mary Jane, at index 1, is second.

    Complexity

    Time: O(n). There are two loops, each visiting every employee at most once, so the total is about 2n steps. Space: O(1), since the program only adds two indexes and two bonuses. Sorting would cost O(n log n) and isn't needed for the top two.

    Testing

    Keeping the names and salaries from the starter data and changing only the productivities:

    ProductivitiesOutput
    83, 133, 97, 150, 120Alice Chen: $37500, then Mary Jane: $50250
    150, 83, 97, 150, 120John Doe: $20250, then Alice Chen: $37500
    100, 100, 100, 100, 100John Doe: $20250, then Mary Jane: $50250
    200, 133, 97, 150, 120John Doe: $20250, then Alice Chen: $37500

    With only two employees, Array("A", "B"), productivities 5 and 9 and salaries 100000 and 200000, the output is B: $30000 and then A: $15000.

    Edge cases and common mistakes

    • Ties for first place. In the second row, John Doe and Alice Chen both have 150. John Doe is first, because he is listed first. Alice Chen then becomes second best, since she is the best among the others. A tied employee is not lost.
    • All equal. In the third row, the earliest employee wins, and the earliest of the others, Mary Jane, is second.
    • Forgetting to skip the winner. Without i != bestIndex, the second pass finds the winner again and prints the same line twice.
    • Starting the second loop at 1. If the winner is employee 0, that is harmless, but if the winner is somewhere else, employee 0 is never considered for second place.
    • Starting secondIndex at 0. If employee 0 is the winner, the second pass would begin with the winner as the second-place candidate and might never replace them.
    • Fewer than two employees. With one employee, secondIndex stays at -1, and salaries(secondIndex) throws an ArrayIndexOutOfBoundsException. This version assumes at least two employees.

    Key takeaways

    • The second best is the best of everyone except the winner, so two simple scans replace a sort.
    • A value such as -1 can mean "no choice yet" because it is not a valid index.
    • Put the check for that marker first in an ||, so the array is never read at -1.
    • The next version builds on this one.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free