Start learning free

LESSON 186 OF 291 · LOOPING OVER ARRAY INDICES

Employee of the Year V5 in Kotlin: Top Two with Two Loops

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 = 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)

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 = 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)

        var bestIndex = 0
        for (i in 1 until names.size) {
            if (productivities[i] > productivities[bestIndex]) {
                bestIndex = i
            }
        }
        var secondIndex = -1
        for (i in 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

    KOTLIN · LOOPING OVER ARRAY INDICES

    Employee Of The Year V5 in Kotlin, explained

    Problem overview

    This version awards bonuses to the two most productive employees. The data is the same set of parallel arrays as before: names, productivities and salaries, where index i in all three describes one employee. The program prints two lines, best employee first, each in the form name: $bonus. Each bonus is 15% of the salary, rounded down. If two employees have the same productivity, the one listed first ranks higher.

    On the lesson's data, Alice Chen has the highest productivity (150) and Mary Jane the next highest (133):

    Alice Chen: $37500
    Mary Jane: $50250
    

    No sorting is needed. The previous version found the best employee with a loop, and this one adds a second loop for the runner-up.

    Approach

    The second best employee is the best among everyone except the first. So the plan is two passes:

    1. Find bestIndex with the loop from version 4.
    2. Find secondIndex with a similar loop that skips bestIndex.

    The second loop has one problem the first doesn't have. The first loop could start by assuming employee 0 is the best. But employee 0 might be the best, in which case they can't also be the starting point for second place. The solution is to start secondIndex at -1, which is no valid index and so means "nobody chosen yet", and to let the first eligible employee take the spot.

    Step by step

    1. Create bestIndex as a var at 0.
    2. Loop i over 1 until names.size. Employee 0 is the best so far, so the loop starts at 1.
    3. Replace bestIndex on a strictly higher productivity. Strictly greater keeps the earlier employee on a tie.
    4. Create secondIndex as a var at -1.
    5. Write a second loop over 0 until names.size. It starts at 0 because the best employee can be anywhere, and the loop skips them with a test instead of a different start.
    6. Write the condition inside it. The employee must not be the best (i != bestIndex), and either nobody is chosen yet (secondIndex == -1) or the employee's productivity is strictly greater than that of secondIndex. When it all holds, set secondIndex = i.
    7. Calculate bestBonus from salaries[bestIndex] with the integer formula.
    8. Calculate secondBonus the same way from salaries[secondIndex].
    9. Print the best employee as the name, a colon, a dollar sign and the bonus.
    10. Print the second best the same way on the next line.

    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)
    
            var bestIndex = 0
            for (i in 1 until names.size) {
                if (productivities[i] > productivities[bestIndex]) {
                    bestIndex = i
                }
            }
            var secondIndex = -1
            for (i in 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)
    

    How the second loop runs

    On the lesson's data, bestIndex ends at 3 (Alice Chen). Here is secondIndex after each pass of the second loop:

    start secondIndex=-1
    i=0 (83) secondIndex=0
    i=1 (133) secondIndex=1
    i=2 (97) secondIndex=1
    i=3 (150) secondIndex=1
    i=4 (120) secondIndex=1
    

    At i = 0 nobody is chosen, so John Doe takes the spot. At i = 1 Mary Jane's 133 beats 83. Employees 2 and 4 don't beat 133, and at i = 3 the check i != bestIndex is false, so Alice Chen is skipped no matter her score. The loop ends with secondIndex equal to 1.

    Kotlin details

    • && and || together. && binds tighter than ||, and the parentheses around the || part make the intent clear: "not the best, and (nobody yet or better than the current second)".
    • Short-circuit evaluation. In secondIndex == -1 || productivities[i] > productivities[secondIndex], when secondIndex is -1 the left side is true and the right side is never evaluated. That matters, because productivities[-1] would throw ArrayIndexOutOfBoundsException.
    • Why the order of the sentinel check matters. The -1 test must come before the productivity comparison in the ||, so the array is never indexed with -1.
    • String concatenation. names[bestIndex] + ": $" + bestBonus joins a String, a literal and an Int from left to right. The $ before a closing quote is an ordinary character.
    • Arrays. names is an Array<String> and the other two are IntArrays. All three use [i] and .size.

    Complexity

    Each loop visits every employee once, so the time is O(n) for n employees, with two passes. The extra space is O(1): two indexes and two bonuses.

    Edge cases and common mistakes

    • Ties for first. With productivities 150, 150, 97, 150 and 120, the best is employee 0 (the first 150). In the second loop, employee 1 (also 150) takes second place, and employee 3 (150) doesn't replace them because it isn't strictly greater. The output is John Doe: $20250 and Mary Jane: $50250.
    • Best employee first in the list. With productivity 200 at index 0, the second loop must skip index 0 and finds Alice Chen with 150. The output is John Doe: $20250 then Alice Chen: $37500. Starting the second loop at 1 instead of using the i != bestIndex test would break cases like this one.
    • All productivities equal. The best is employee 0, the second is employee 1.
    • Fewer than two employees. With a single employee, secondIndex stays -1, and salaries[secondIndex] throws ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 1. The lesson's data has five employees, so this doesn't arise, but the -1 is exactly what tells you nobody was chosen.
    • Forgetting to skip the best. Without i != bestIndex the second loop just finds the best employee again and prints the same line twice.
    • Comparing with >=. In the second loop that would let a later employee replace an earlier one with the same productivity, breaking the "listed first wins" rule.

    Testing

    Change the productivity values in the editor above and compare:

    productivitiesoutput
    83, 133, 97, 150, 120Alice Chen: $37500, then Mary Jane: $50250
    150, 150, 97, 150, 120John Doe: $20250, then Mary Jane: $50250
    200, 133, 97, 150, 120John Doe: $20250, then Alice Chen: $37500
    10, 10, 10, 10, 10John Doe: $20250, then Mary Jane: $50250
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free