Start learning free

LESSON 253 OF 285 · NESTED LOOPS

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

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

Build:

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

Rules:

  • Index i in all three slices 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: taken := make([]bool, len(names)). 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.

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

taken := make([]bool, len(names))
for rank := 0; rank < k; rank++ {
    bestIndex := -1
    for i := 0; i < len(names); i++ {
        if !taken[i] && (bestIndex == -1 || productivities[i] > productivities[bestIndex]) {
            bestIndex = i
        }
    }
    if bestIndex != -1 {
        taken[bestIndex] = true
        bonus := salaries[bestIndex] * 15 / 100
        fmt.Println(names[bestIndex] + ": $" + strconv.Itoa(bonus))
    }
}

STEP 1 OF 9
    Ctrl + Enter to check

    GO · NESTED LOOPS

    Employee Of The Year V6 in Go, explained

    Problem overview

    The final version of the project gives bonuses to the top k most productive employees, where k is a variable. The data is three parallel slices, so index i in each one is the same person, plus k:

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

    Each bonus is 15% of the salary, rounded down. The program prints one line per winner, best first, as name: $bonus. On a tie in productivity the employee listed first wins. The output for k = 3 is:

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

    The program must keep working when k changes. If k is larger than the number of employees, everybody wins once, and the extra rounds print nothing.

    Approach: repeat the search, remember the winners

    The lesson doesn't sort. Instead it repeats the search for the best employee k times. A single search is a loop that keeps the index of the best candidate so far and replaces it only when it finds a strictly higher productivity, so ties stay with the earlier employee. Repeating it alone would find Alice Chen every time. To make each round find the next best, the program keeps a bool flag for each employee: taken[i] says that employee i has already won. Each round skips the taken employees, and the winner of the round is marked as taken.

    Each round starts a new search with bestIndex at -1, meaning nobody chosen yet. It can't start at 0, because employee 0 may already be taken, and the search must not compare against a winner from an earlier round. An employee becomes the round's best if they are not taken, and either nobody is chosen yet or their productivity is strictly higher than the current best's.

    After the search, bestIndex is still -1 only if every employee is taken. That happens when k is larger than the number of employees, and in that case the round prints nothing.

    On the starting data the three rounds pick Alice Chen (150), Mary Jane (133) and Carlos Diaz (120), in that order.

    Step by step

    1. Create taken. make([]bool, len(names)) makes a slice with one bool per employee, all false.
    2. Write the rounds loop. for rank := 0; rank < k; rank++ { runs k times. The counter only counts the rounds. Close the brace right away.
    3. Start the round with bestIndex := -1. It is declared inside the loop, so every round starts with nobody chosen.
    4. Write the inner loop over i from 0 to len(names). It looks at everybody every time, and the taken ones are skipped in the next step.
    5. Write the condition. !taken[i], and either bestIndex == -1 or productivities[i] > productivities[bestIndex]. When it holds, assign bestIndex = i.
    6. Check that somebody was found, with if bestIndex != -1, after the inner loop. This guards the rounds when k is too large.
    7. Mark the winner by setting taken[bestIndex] to true. It must happen right away, because the next round reads it.
    8. Compute bonus from the winner's salary: salaries[bestIndex] * 15 / 100. Multiplying before dividing keeps the precision, and integer division rounds the result down.
    9. Print the winner as the name, ": $" and the bonus converted with strconv.Itoa.

    The solution in Go

    names := []string{"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"}
    productivities := []int{83, 133, 97, 150, 120}
    salaries := []int{135000, 335000, 210000, 250000, 180000}
    k := 3
    
    taken := make([]bool, len(names))
    for rank := 0; rank < k; rank++ {
        bestIndex := -1
        for i := 0; i < len(names); i++ {
            if !taken[i] && (bestIndex == -1 || productivities[i] > productivities[bestIndex]) {
                bestIndex = i
            }
        }
        if bestIndex != -1 {
            taken[bestIndex] = true
            bonus := salaries[bestIndex] * 15 / 100
            fmt.Println(names[bestIndex] + ": $" + strconv.Itoa(bonus))
        }
    }
    

    The code uses the fmt and strconv packages. A few Go details:

    • Zero values. make([]bool, n) fills the slice with false, the zero value of bool. No loop is needed to initialise it.
    • Short-circuit operators. && and || stop as soon as the answer is known. When bestIndex == -1 is true, the right side of the || is never evaluated, so productivities[bestIndex] with index -1 is not read. The order of the two tests matters here. Indexing a slice at -1 panics at run time.
    • Precedence. && binds tighter than ||, so the parentheses around the || part are needed. Without them the condition would mean something else: "not taken and nobody chosen yet, or a higher productivity".
    • Slices are mutable in place. taken[bestIndex] = true changes the slice that the next round reads.
    • Money as int. salaries[bestIndex] * 15 / 100 is integer arithmetic on whole numbers. Go evaluates * and / from left to right, so the multiplication happens first.
    • $ is just a character inside the string ": $".

    Complexity

    Time is O(k * n) for n employees: each of the k rounds scans all n. When k is much larger than n, the extra rounds still scan everybody and find nobody, so the cost is still k * n operations, though nothing is printed. Sorting would cost O(n log n), which is better when k is large, but this lesson practises the repeated search. Space is O(n) for the taken slice.

    Edge cases and common mistakes

    • No taken flags. Every round finds the same employee: two rounds without the flags both print Alice Chen.
    • k larger than the team. With k = 7 and five employees, the output is five lines, from Alice Chen down to John Doe. The guard bestIndex != -1 is what stops the sixth round. Without it, taken[bestIndex] panics with index out of range [-1].
    • Starting bestIndex at 0. In the later rounds employee 0 may be taken, and the search would start from a winner.
    • Ties. With productivities 100, 100, 100 and 90, the first three rounds pick the employees in listed order, so a tie never reorders them. The comparison must be strict (>).
    • Declaring bestIndex outside the rounds loop. It would keep the previous winner and never be reset.
    • k of 0. The loop doesn't run and nothing is printed.
    • Rounding. A salary of 100001 gives a bonus of 15000, not 15000.15, because the division drops the fraction.

    Testing

    With the starting data and different values of k:

    • k = 1 prints Alice Chen: $37500.
    • k = 2 prints that line and Mary Jane: $50250.
    • k = 5 prints Alice Chen, Mary Jane, Carlos Diaz ($27000), Bob Smith ($31500) and John Doe ($20250).
    • k = 7 prints the same five lines as k = 5.
    • k = 0 prints nothing.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free