Start learning free

LESSON 253 OF 291 · NESTED LOOPS

Employee of the Year V6 in Scala: Top K Bonuses 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:

        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)
        val 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 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: val taken = new Array[Boolean](names.size). 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.

        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)
        val k = 3

        val taken = new Array[Boolean](names.size)
        for (rank <- 0 until k) {
            var bestIndex = -1
            for (i <- 0 until names.size) {
                if (!taken(i) && (bestIndex == -1 || productivities(i) > productivities(bestIndex))) {
                    bestIndex = i
                }
            }
            if (bestIndex != -1) {
                taken(bestIndex) = true
                val bonus = salaries(bestIndex) * 15 / 100
                println(names(bestIndex) + ": $" + bonus)
            }
        }

STEP 1 OF 9
    Ctrl + Enter to check

    SCALA · NESTED LOOPS

    Employee Of The Year V6 in Scala, explained

    Problem overview

    The starter code describes five employees with three parallel arrays: names, productivities and salaries. Index i in each array is the same person. A variable k, here 3, says how many people receive a bonus. The bonus is 15 percent of the salary, rounded down, and the winners are the k most productive employees, printed best first as name: $bonus.

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

    Sorting is off limits. Instead the program repeats a search for the best employee k times, and remembers who already won so nobody wins twice. If two employees tie on productivity, the one listed first wins. If k is larger than the number of employees, everybody wins once and the extra rounds print nothing. This version generalises the previous one to any k.

    Approach

    One round is a linear scan: go through all employees, keep the index of the best one seen so far, and replace it only when someone has strictly higher productivity. The strict comparison is what makes ties go to the earlier employee, since a later employee with an equal value doesn't replace the current best.

    To run the scan again for the second-best, the program must ignore the first winner. A Boolean array called taken, one slot per employee, records who has won. A scan skips every employee whose slot is true.

    The program does k rounds, each scanning n employees, so the time is O(k * n), which is fine for small k. A sort would cost O(n log n) regardless of k, but the lesson practises the nested-loop pattern.

    Step by step

    1. Create taken. new Array[Boolean](names.size) makes an array with one slot per employee. A new array of Boolean starts with every slot false: nobody has won yet.
    2. Write the outer loop. for (rank <- 0 until k) runs once per winner. rank only counts the rounds.
    3. Start each round with bestIndex = -1. Since -1 is not an index of any employee, it means nobody chosen yet. Declaring it inside the outer loop resets it every round.
    4. Write the inner loop over every employee position, 0 until names.size.
    5. Test each candidate. The employee must not have won (!taken(i)), and either no one is chosen yet or the productivity is strictly greater than the current best's. If both hold, set bestIndex to i.
    6. Check that someone was found once the inner loop ends: bestIndex != -1. When k exceeds the number of employees, the last rounds find nobody, and using -1 as an index would crash.
    7. Mark the winner by setting taken(bestIndex) to true, so the next round skips them.
    8. Compute the bonus: salaries(bestIndex) * 15 / 100. The multiplication comes first and the division rounds down.
    9. Print the winner with the name at the same index and the bonus.

    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)
    val k = 3
    
    val taken = new Array[Boolean](names.size)
    for (rank <- 0 until k) {
        var bestIndex = -1
        for (i <- 0 until names.size) {
            if (!taken(i) && (bestIndex == -1 || productivities(i) > productivities(bestIndex))) {
                bestIndex = i
            }
        }
        if (bestIndex != -1) {
            taken(bestIndex) = true
            val bonus = salaries(bestIndex) * 15 / 100
            println(names(bestIndex) + ": $" + bonus)
        }
    }
    

    Details that matter in Scala

    The condition !taken(i) && (bestIndex == -1 || productivities(i) > productivities(bestIndex)) relies on short-circuit evaluation. With && and ||, the right side runs only when needed. When bestIndex is -1, the left side of the || is true, so productivities(bestIndex) is never evaluated. Swapping the two parts of the || would read productivities(-1) and throw.

    The string ": $" contains a dollar sign, which is harmless in a plain string. It matters only in an s string, where $ starts an interpolation and a literal dollar sign is written $$. For example s"$name: $$$bonus" prints the same line as the solution does: Alice Chen: $37500.

    Arrays in Scala are mutable, and taken(bestIndex) = true changes a slot in place. The array's size stays fixed, which is all this program needs.

    Integer division and overflow

    The bonus is an Int calculation. A salary of 10001 gives 10001 * 15 / 100 = 1500, where the exact bonus would be 1500.15, so the cents are dropped. An Int holds values up to 2,147,483,647 and wraps silently past that. Multiplying first is safe for the salaries in this lesson, but a salary of 200,000,000 gives 200000000 * 15 / 100 = -12949672. Converting to Long first, salary.toLong * 15 / 100, gives the right 30000000.

    Edge cases and common mistakes

    • Different values of k. With k = 1 only Alice Chen prints. With k = 2 it is Alice Chen and Mary Jane. With 5 or 7, all five employees print: Alice Chen, Mary Jane, Carlos Diaz, Bob Smith and John Doe, each once. With 0 nothing prints.
    • Ties. With productivities of 100, 100 and 90 for A, B and C, and k = 2, A wins first and B second. A later employee must beat the best strictly, so use >, not >=.
    • Forgetting to mark the winner. Without taken(bestIndex) = true, every round finds the same employee and prints him or her k times.
    • Resetting bestIndex outside the outer loop. A stale index from the last round would make the next round compare against a winner who is already taken.
    • Skipping the -1 check. The case where k is larger than the number of employees would throw an ArrayIndexOutOfBoundsException at index -1.

    Key takeaways

    • Repeat a "find the best" scan k times, and skip earlier winners with a flag array.
    • A strict comparison keeps the first of equal values.
    • Use -1 as "none yet" and check it before indexing with it.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free