Start learning free

LESSON 253 OF 291 · NESTED LOOPS

Employee of the Year V6 in Kotlin: Top K 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 = arrayOf("John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz")
        val productivities = intArrayOf(83, 133, 97, 150, 120)
        val salaries = intArrayOf(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 = BooleanArray(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 = arrayOf("John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz")
        val productivities = intArrayOf(83, 133, 97, 150, 120)
        val salaries = intArrayOf(135000, 335000, 210000, 250000, 180000)
        val k = 3

        val taken = BooleanArray(names.size)
        for (rank in 0 until k) {
            var bestIndex = -1
            for (i in 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

    KOTLIN · NESTED LOOPS

    Employee Of The Year V6 in Kotlin, explained

    Problem overview

    Three parallel arrays describe the staff: names[i], productivities[i] and salaries[i] all belong to employee i. This version gives a bonus to the top k most productive employees, where k is a variable. The bonus is 15% of the salary, rounded down. The program prints one line per winner, best first, in the form name: $bonus. The previous version rewarded only the single best employee; the next version builds on this one.

    The starter code has five employees and k = 3:

    indexnameproductivitysalary
    0John Doe83135000
    1Mary Jane133335000
    2Bob Smith97210000
    3Alice Chen150250000
    4Carlos Diaz120180000

    The three highest productivities are 150 (Alice), 133 (Mary) and 120 (Carlos), so the output is:

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

    Approach

    The lesson forbids sorting. Sorting the productivities would also scramble their link to the names and salaries, because the arrays are parallel. Instead, the program repeats the search for the maximum once per winner, and each round ignores the employees who already won.

    That needs a memory of who has won. A BooleanArray with one slot per employee does it: taken[i] is true once employee i has a bonus. Each round scans everybody, skips the taken ones, and keeps the position of the best of the rest in bestIndex. One position gives the name, the productivity and the salary at once.

    On the lesson's data the rounds go like this: round 0 picks index 3 (150), round 1 picks index 1 (133), and round 2 picks index 4 (120), because indices 3 and 1 are now taken and 120 is the highest productivity left.

    Step by step

    1. Create taken as BooleanArray(names.size). Every slot starts as false, since nobody has won yet.
    2. Write the round loop. for (rank in 0 until k) runs k times. The counter only counts rounds; the loop never reads it.
    3. Reset bestIndex to -1 inside the round. No employee has index -1, so it means "nobody chosen yet", and creating it inside the loop restarts the search every round.
    4. Write the inner loop over 0 until names.size: every employee is looked at again in every round.
    5. Test each employee. They become the round's best when they are not taken, and either nobody is chosen yet or their productivity is strictly greater than the current best's. Strictly greater means the employee listed first wins a tie.
    6. Check that someone was found after the inner loop. When k exceeds the number of employees, the last rounds find nobody, bestIndex is still -1, and they must print nothing.
    7. Mark the winner with taken[bestIndex] = true. The next round reads this flag.
    8. Compute the bonus as the salary times 15, divided by 100.
    9. Print the line with the name at the winner's index and the bonus.

    The solution in Kotlin

            val names = arrayOf("John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz")
            val productivities = intArrayOf(83, 133, 97, 150, 120)
            val salaries = intArrayOf(135000, 335000, 210000, 250000, 180000)
            val k = 3
    
            val taken = BooleanArray(names.size)
            for (rank in 0 until k) {
                var bestIndex = -1
                for (i in 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)
                }
            }
    

    Kotlin details worth a look:

    • Short-circuit conditions. && and || stop as soon as the answer is known. When bestIndex is -1, the right side of || is never evaluated, so productivities[bestIndex] is never read with an invalid index. The order of the two tests matters.
    • BooleanArray. BooleanArray(3) holds false, false, false. Like intArrayOf, it is a primitive array, and you change a slot with taken[i] = true.
    • 0 until k. The end is excluded, so k = 3 gives 0, 1 and 2. With k = 0 the range is empty and nothing prints.
    • The $ in the output. In ": $" the dollar sign is followed by a quote, so it is plain text and not a template. The number is joined with +, which turns the Int into text because the left side is a String.
    • Integer arithmetic. salaries[bestIndex] * 15 / 100 multiplies first and then divides, and Int division drops the remainder, which gives the rounding down the task asks for.

    Complexity

    Time: O(k * n) for n employees, because each of the k rounds scans all n. With k = n that is O(n²). Sorting would be O(n log n), but this lesson practises the nested loop. Space: O(n) for the taken array.

    Edge cases and common mistakes

    • Forgetting the taken flags. Without them every round finds the same employee, and the program prints Alice Chen three times.
    • Skipping the -1 check. With k = 7 and five employees, rounds 5 and 6 find nobody. Using bestIndex anyway throws ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5. With the check, k = 5 and k = 7 both print the same five lines, ending with Bob Smith and John Doe.
    • Other values of k. For k = 1 the output is only Alice Chen: $37500, and for k = 2 it is the first two lines of the example.
    • Ties. Employees with equal productivity are taken in listing order, so the earlier one wins first. With > replaced by >=, the later one would win.
    • Resetting too late. Declaring bestIndex before the round loop keeps the previous winner's index, and the search compares against an employee who is already taken.
    • Overflow in the bonus. Int wraps silently above about 2.1 billion, and salary * 15 reaches that for salaries above 143,165,576. A salary of 2,000,000,000 gives -647710 with Int arithmetic, but 300,000,000 when the salary is converted to Long first. The lesson's salaries are far below the limit.

    Testing

    changeoutput
    k = 3, the starter dataAlice Chen: $37500, Mary Jane: $50250, Carlos Diaz: $27000
    k = 1Alice Chen: $37500
    k = 0no output
    k = 5 or k = 7the three lines above, then Bob Smith: $31500 and John Doe: $20250
    A, B, C with productivity 50, 50, 40; salaries 100000, 200000, 300000; k = 3A: $15000, B: $30000, C: $45000
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free