Start learning free

LESSON 254 OF 292 · NESTED LOOPS

Employee of the Year V6 in Swift: 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:

        let names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"]
        let productivities = [83, 133, 97, 150, 120]
        let salaries = [135000, 335000, 210000, 250000, 180000]
        let 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: var taken = Array(repeating: false, count: names.count). 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.

        let names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"]
        let productivities = [83, 133, 97, 150, 120]
        let salaries = [135000, 335000, 210000, 250000, 180000]
        let k = 3

        var taken = Array(repeating: false, count: names.count)
        for rank in 0..<k {
            var bestIndex = -1
            for i in 0..<names.count {
                if !taken[i] && (bestIndex == -1 || productivities[i] > productivities[bestIndex]) {
                    bestIndex = i
                }
            }
            if bestIndex != -1 {
                taken[bestIndex] = true
                let bonus = salaries[bestIndex] * 15 / 100
                print(names[bestIndex] + ": $" + String(bonus))
            }
        }

STEP 1 OF 9
    Ctrl + Enter to check

    SWIFT · NESTED LOOPS

    Employee Of The Year V6 in Swift, explained

    Problem overview

    The data is three parallel arrays, names, productivities and salaries, where index i describes one employee. This version awards bonuses to the top k most productive employees, where k is a variable: k = 3 in the starter code, but the program must keep working for 1, 2, 5, 7 or any other value. Sorting is still off the table. The program repeats the search for the best employee k times and remembers who has already won, so nobody wins twice.

    Each bonus is 15% of the salary, rounded down, and each winner gets a line name: $bonus, best first. If two employees are equally productive, the one listed first wins. For the starter data the output is:

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

    If k is larger than the number of employees, everybody wins once and the extra rounds print nothing.

    Approach: one search per round, with a "taken" flag

    The previous version found the best and the second best with two hand-written loops. That doesn't scale to a variable k, so this version writes the search once and wraps it in a loop that runs k times.

    Each round needs to ignore the people who already won. A Bool array named taken, with one slot per employee, records this: taken[i] is true once employee i has won. A round considers only the employees whose flag is still false, and when it picks a winner it flips that flag so later rounds skip them.

    Inside a round, bestIndex starts at -1, meaning "nobody chosen yet". An employee becomes the round's best when they haven't won and either nobody is chosen yet or their productivity is strictly higher than the current best's. Strictly higher is what makes the first listed employee win a tie.

    The rounds on the starter data

    RoundbestIndexWinnertaken after the round
    03Alice Chen (150)[false, false, false, true, false]
    11Mary Jane (133)[false, true, false, true, false]
    24Carlos Diaz (120)[false, true, false, true, true]

    Round 1 skips index 3 because it is taken, so Mary Jane (133) beats everybody who is left. Round 2 skips indices 1 and 3, and Carlos Diaz (120) beats Bob Smith (97) and John Doe (83).

    Step by step

    1. Create taken with Array(repeating: false, count: names.count). It is a var because the flags change. Nobody has won yet, so every slot is false.
    2. Write the rounds loop, for rank in 0..<k. The counter only counts rounds; it is not used inside the loop.
    3. Start each round with var bestIndex = -1. It is created inside the loop so every round begins with nobody chosen.
    4. Write the inner loop over 0..<names.count. Every round looks at all employees again.
    5. Test each employee. They must not have won (!taken[i]), and either bestIndex == -1 or their productivity is strictly greater than that of bestIndex. If so, bestIndex = i.
    6. Check that someone was found with bestIndex != -1. When k is larger than 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 straight away, because the next round reads it.
    8. Compute the bonus as salaries[bestIndex] * 15 / 100. Integer division rounds the result down.
    9. Print the winner as the name, ": $" and the bonus converted with String(...).

    The solution in Swift

    let names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"]
    let productivities = [83, 133, 97, 150, 120]
    let salaries = [135000, 335000, 210000, 250000, 180000]
    let k = 3
    
    var taken = Array(repeating: false, count: names.count)
    for rank in 0..<k {
        var bestIndex = -1
        for i in 0..<names.count {
            if !taken[i] && (bestIndex == -1 || productivities[i] > productivities[bestIndex]) {
                bestIndex = i
            }
        }
        if bestIndex != -1 {
            taken[bestIndex] = true
            let bonus = salaries[bestIndex] * 15 / 100
            print(names[bestIndex] + ": $" + String(bonus))
        }
    }
    

    Swift specifics worth knowing:

    • Array(repeating:count:) builds an array of that many copies of a value. Arrays are value types, so taken[bestIndex] = true changes taken in place and needs the var.
    • String(bonus) is needed for +. Swift doesn't join a String and an Int with +. Writing "Alice" + ": $" + bonus is a compile error: binary operator '+' cannot be applied to operands of type 'String' and 'Int'. String interpolation, "\(names[bestIndex]): $\(bonus)", is the other common way.
    • The condition's grouping. The parentheses make the "nobody yet or higher" test one unit that is combined with !taken[i]. && binds tighter than ||, so without them the meaning would change.
    • Short-circuiting. When bestIndex == -1 is true, Swift doesn't evaluate productivities[bestIndex], so the -1 is never used as an index in that test.
    • The unused counter. Because rank is never read, the compiler warns that the value was never used and suggests _. It is a warning, not an error, and the program runs.
    • 0..<k is empty when k is 0. The loop body never runs and nothing is printed. A negative k would crash, because a range can't end before it starts.

    Edge cases and common mistakes

    • k larger than the number of employees. With k = 7 and five employees, the output is five lines, one per employee, from Alice Chen down to John Doe. Rounds 5 and 6 find nobody, so the bestIndex != -1 check keeps them silent.
    • Ties. With productivities [10, 20, 20] and k = 2, the second and third employees are tied. The one listed first wins round 0 and the other wins round 1. Using >= instead of > would reverse that.
    • Forgetting to mark the winner. If taken is never updated, every round finds the same employee and prints the same line k times.
    • Creating bestIndex outside the rounds loop. The value from the previous round would stay, and the new round would start with a champion that has already won.
    • Using bestIndex without the check. That works while k is small and crashes when k is larger than the number of employees.

    Testing

    These outputs come from the solution with other values of k on the starter data.

    • k = 1 prints Alice Chen: $37500.
    • k = 2 prints Alice Chen: $37500 and Mary Jane: $50250.
    • k = 5 and k = 7 both print five lines: Alice Chen $37500, Mary Jane $50250, Carlos Diaz $27000, Bob Smith $31500 and John Doe $20250.
    • k = 0 prints nothing.

    Change k in the editor above and compare with these lines.

    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free