Start learning free

LESSON 186 OF 285 · LOOPING OVER ARRAY INDICES

Employee of the Year V5 in Go: Top Two Without Sorting

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:

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}

Build:

Alice Chen: $37500
Mary Jane: $50250

Rules:

  • Index i in all three slices 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.

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}

bestIndex := 0
for i := 1; i < len(names); i++ {
    if productivities[i] > productivities[bestIndex] {
        bestIndex = i
    }
}
secondIndex := -1
for i := 0; i < len(names); i++ {
    if i != bestIndex && (secondIndex == -1 || productivities[i] > productivities[secondIndex]) {
        secondIndex = i
    }
}
bestBonus := salaries[bestIndex] * 15 / 100
secondBonus := salaries[secondIndex] * 15 / 100
fmt.Println(names[bestIndex] + ": $" + strconv.Itoa(bestBonus))
fmt.Println(names[secondIndex] + ": $" + strconv.Itoa(secondBonus))

STEP 1 OF 10
    Ctrl + Enter to check

    GO · LOOPING OVER ARRAY INDICES

    Employee Of The Year V5 in Go, explained

    Problem overview

    Version 5 hands out bonuses to the two most productive employees, best first. The data is the same three parallel slices as in version 4, names, productivities and salaries, where index i in each slice is the same person. Each bonus is 15% of the salary, rounded down. Ties go to whoever is listed first. The output has one line per employee, written as name: $bonus:

    Alice Chen: $37500
    Mary Jane: $50250
    

    Alice Chen (150) is the best and Mary Jane (133) is second, since 133 is the highest productivity among everyone else. The lesson does not use sorting: it uses the loop from version 4 twice.

    Approach: find the best, then find the best of the rest

    The first loop is the version 4 loop. It finds bestIndex, the position of the most productive employee, and on a tie keeps the earlier one because it compares strictly.

    The second loop looks for the best among the other employees. It is the same search, with one addition: it skips bestIndex. There is a catch, though. The loop cannot start with secondIndex := 0 as the first loop did, because position 0 might itself be the best employee, who is not allowed to be second. So secondIndex starts at -1, meaning nobody is chosen yet. No employee has that index, so it is a safe marker.

    An employee at position i becomes the second best when two things hold: the employee is not the best one, and either nobody is chosen yet or the employee's productivity is strictly greater than that of the current second. The first employee to pass the first test is taken without a comparison, and later ones have to beat them.

    On the starting data the first loop gives bestIndex 3 (Alice Chen, 150). The second loop visits 0 (83, taken as the first candidate), 1 (133 beats 83), 2 (97 does not beat 133), skips 3, and at 4 (120) does not beat 133. It ends with secondIndex equal to 1, Mary Jane.

    Step by step

    1. Find the best. Steps 1 to 3 repeat version 4: bestIndex := 0, a loop from 1 to len(names), and an if with a strict > on productivity.
    2. Start the second place at -1: secondIndex := -1, "nobody yet".
    3. Write a second loop from 0. It starts at 0 rather than 1 because the best employee may sit anywhere, so the loop skips them by a check, not by its range.
    4. Write the combined test. The employee must differ from the best, written i != bestIndex, and either secondIndex == -1 or productivities[i] > productivities[secondIndex]. When all of that holds, set secondIndex = i.
    5. Compute both bonuses, bestBonus and secondBonus, from the salaries at the two indexes, multiplying by 15 before dividing by 100.
    6. Print the best employee as the name, ": $" and the bonus converted with strconv.Itoa.
    7. Print the second the same way on the next line.

    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}
    
    bestIndex := 0
    for i := 1; i < len(names); i++ {
        if productivities[i] > productivities[bestIndex] {
            bestIndex = i
        }
    }
    secondIndex := -1
    for i := 0; i < len(names); i++ {
        if i != bestIndex && (secondIndex == -1 || productivities[i] > productivities[secondIndex]) {
            secondIndex = i
        }
    }
    bestBonus := salaries[bestIndex] * 15 / 100
    secondBonus := salaries[secondIndex] * 15 / 100
    fmt.Println(names[bestIndex] + ": $" + strconv.Itoa(bestBonus))
    fmt.Println(names[secondIndex] + ": $" + strconv.Itoa(secondBonus))
    

    The code uses the fmt and strconv packages.

    The details worth knowing

    • Short-circuit evaluation. In secondIndex == -1 || productivities[i] > productivities[secondIndex], Go skips the right side when the left side is true. That matters here: while secondIndex is -1, evaluating productivities[secondIndex] would panic with index out of range [-1]. The order of the two operands is what keeps it safe. && short-circuits the same way, on a false left side.
    • The parentheses. && binds tighter than ||. Without the parentheses, the condition would read as (i != bestIndex && secondIndex == -1) || ..., and the best employee could be picked as second through the right-hand part.
    • Using -1 as a marker. Slice indexes in Go start at 0 and an int can hold -1, so the value never collides with a real position.
    • != compares the two integers. The check i != bestIndex compares positions, not productivities, so two employees with the same productivity are still told apart.

    Complexity

    Time is O(n): two passes over the slices, each with constant work per element, which is 2n steps. Extra space is O(1): a few integers. Sorting would cost O(n log n) and would also reorder the slices, which would then have to be kept aligned.

    Edge cases and common mistakes

    • Ties for first place. With productivities {150, 150, 97}, bestIndex is 0. The second loop skips position 0, takes position 1 as the first candidate, and position 2 (97) does not beat it. The second place is employee 1, who is as productive as the best.
    • A tie for second. The strict > keeps the earlier employee as second.
    • Fewer than two employees. With a single employee, the second loop skips them and secondIndex stays -1. Reading salaries[secondIndex] then panics with index out of range [-1]. The lesson's data has five employees.
    • Starting secondIndex at 0. When the best employee is at position 0, the second place would start as the best employee.
    • Dropping the i != bestIndex check. Then the best employee would be reported twice.
    • Swapping the output lines. The best employee comes first.

    Testing

    • The starting data prints Alice Chen: $37500 and Mary Jane: $50250.
    • Productivities {150, 140, 130, 120, 110} print John Doe: $20250 and Mary Jane: $50250.
    • Productivities {150, 150, 97, 100, 120} print John Doe: $20250 and Mary Jane: $50250.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free