Start learning free

LESSON 254 OF 285 · NESTED LOOPS

Top K Brands V4 in Go: Repeated Search for the Top K

Practice Read the full explanation

Show the top k brands by rating. This is v3's search, repeated k times: find the best brand, mark it as taken, then search again among the brands that are not taken yet, until you have k brands in rank order.

You start with:

brands := []string{"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"}
ratings := []int{4, 5, 3, 5, 4}
k := 3

Build:

1. MegaCorp (5)
2. NeoByte (5)
3. TechPro (4)

Rules:

  • Repeat v3's search k times. Each round looks only at brands that are not taken yet and picks the one with the highest rating, then marks it as taken (one true/false flag per brand).
  • Ties go to the brand listed first: keep the first brand you find and replace it only on a strictly higher rating.
  • k is never larger than the number of brands.
  • Each line is "rank. Brand (rating)", starting at rank 1.
  • Print the lines, one per line, with fmt.Println(...).

Start with the two declarations used := make([]bool, len(ratings)) and lines := []string{}. A flag tells whether that position is already taken.

Each round is v3's search: nothing found yet, scan every position, skip taken ones, keep the first candidate and replace it only on a strictly higher rating. Then mark the winner as taken and add its line.

brands := []string{"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"}
ratings := []int{4, 5, 3, 5, 4}
k := 3

used := make([]bool, len(ratings))
lines := []string{}
for rank := 1; rank <= k; rank++ {
    bestIndex := -1
    for i := range ratings {
        if !used[i] {
            if bestIndex == -1 || ratings[i] > ratings[bestIndex] {
                bestIndex = i
            }
        }
    }
    used[bestIndex] = true
    lines = append(lines, strconv.Itoa(rank) + ". " + brands[bestIndex] + " (" + strconv.Itoa(ratings[bestIndex]) + ")")
}
fmt.Println(strings.Join(lines, "\n"))

STEP 1 OF 11
    Ctrl + Enter to check

    GO · NESTED LOOPS

    Top K Brands V4 in Go, explained

    Problem overview

    Version 3 found the single best brand. Version 4 lists the top k brands by rating, best first. The brands and ratings are parallel slices, so brands[i] has the rating ratings[i]:

    brands := []string{"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"}
    ratings := []int{4, 5, 3, 5, 4}
    k := 3
    

    Each output line is rank. Brand (rating), starting at rank 1. When two brands have the same rating, the one listed first comes first. The value of k is never larger than the number of brands. For the starting data the output is:

    1. MegaCorp (5)
    2. NeoByte (5)
    3. TechPro (4)
    

    Approach: run the search k times and mark each winner

    The previous version's search keeps the position of the best brand so far and replaces it only on a strictly higher rating. Running it once gives rank 1. To get rank 2, the same search must ignore the brand that already won. So the program keeps one bool flag per brand, used[i], which says whether brand i already has a rank. Each round searches only the brands that are not used yet, and then marks the winner.

    The search starts each round with bestIndex equal to -1, meaning no brand found yet. It can't start at 0 the way version 3 did, since brand 0 may already be used. A brand is accepted when it is not used and either nothing has been found or its rating is strictly higher than the current best's. Strictness keeps the earlier brand on a tie.

    The rounds on the starting data go like this:

    1. Round 1: TechPro (4) is found first, MegaCorp's 5 beats it, and NeoByte's 5 doesn't beat MegaCorp's, so MegaCorp wins.
    2. Round 2: MegaCorp is skipped. TechPro (4) is found first, then NeoByte (5) beats it, and nothing else does. NeoByte wins.
    3. Round 3: both 5s are used. TechPro (4) is found first, Zenith's 4 doesn't beat it, so TechPro wins.

    This is a loop inside a loop: the outer loop counts ranks and the inner loop searches. For n brands the work is about k * n steps.

    Step by step

    1. Create used. make([]bool, len(ratings)) gives one slot per brand, all false.
    2. Create lines, an empty []string. Each round adds one finished line to it.
    3. Write the rounds loop. for rank := 1; rank <= k; rank++ { counts from 1 up to and including k, so the counter is also the number printed in front of the brand. Close the brace right away.
    4. Set bestIndex := -1 inside it, so each round starts the search over.
    5. Write the inner loop. for i := range ratings { visits each position of the ratings.
    6. Skip used brands with if !used[i] {.
    7. Accept a better brand with if bestIndex == -1 || ratings[i] > ratings[bestIndex] {, strictly greater.
    8. Remember it: bestIndex = i.
    9. Mark the winner after the inner loop with used[bestIndex] = true, so the next round skips it.
    10. Add the line to lines with append: the rank, ". ", the brand name, and the rating in parentheses. The numbers go through strconv.Itoa to be joined to the strings.
    11. Print after the loop, joining the lines with a newline between them.

    The solution in Go

    brands := []string{"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"}
    ratings := []int{4, 5, 3, 5, 4}
    k := 3
    
    used := make([]bool, len(ratings))
    lines := []string{}
    for rank := 1; rank <= k; rank++ {
        bestIndex := -1
        for i := range ratings {
            if !used[i] {
                if bestIndex == -1 || ratings[i] > ratings[bestIndex] {
                    bestIndex = i
                }
            }
        }
        used[bestIndex] = true
        lines = append(lines, strconv.Itoa(rank) + ". " + brands[bestIndex] + " (" + strconv.Itoa(ratings[bestIndex]) + ")")
    }
    fmt.Println(strings.Join(lines, "\n"))
    

    The code uses the fmt, strconv and strings packages. The Go details worth knowing:

    • range over a slice. for i := range ratings with one variable gives the indexes 0 to len(ratings) - 1. It does the same as the counting loop without the bounds to write.
    • make and zero values. The slots of a make([]bool, n) slice are all false.
    • append returns the slice. You must assign it back, lines = append(lines, x), because the result can be a new slice if the old one had no room.
    • The empty slice. []string{} is a slice of length 0 that is ready for append.
    • strings.Join. It glues the elements of a slice with a separator between each two and none at the end. Joined with "\n", the lines print one per line, and fmt.Println adds the final line break.
    • Short-circuit ||. When bestIndex == -1 is true, the right side isn't evaluated, so ratings[bestIndex] never reads index -1.

    Complexity

    Time is O(k * n): each of the k rounds scans all n brands once. Space is O(n + k), for the used flags and the k output lines. Sorting the brands by rating would cost O(n log n), which can be faster when k is large, but the repeated search is simple and needs no ordering of the data.

    Edge cases and common mistakes

    • Ties. With >= instead of >, the later brand replaces the earlier one on a tie, and NeoByte would come before MegaCorp. When all five ratings are 3 and k = 3, the correct output is TechPro, MegaCorp and Quantum, in listed order.
    • Forgetting to mark the winner. Without used[bestIndex] = true, every round finds MegaCorp.
    • Starting bestIndex at 0. If brand 0 is used already, the search starts from a brand that must be skipped.
    • k larger than the number of brands. The lesson promises that it won't happen. If it did, with k = 6 and five brands, the sixth round would find nothing, bestIndex would stay -1 and used[bestIndex] would panic with index out of range [-1].
    • k of 0. The loop doesn't run, lines is empty and fmt.Println prints an empty line.
    • Rank starting at 0. The loop must start at 1 so that the first line is 1. MegaCorp (5).
    • Joining inside the loop. Call strings.Join and print once, after the loop, or the earlier lines would be printed again in every round.

    Testing

    • The starting data with k = 1 prints 1. MegaCorp (5).
    • k = 3 prints MegaCorp (5), NeoByte (5) and TechPro (4).
    • k = 5 adds 4. Zenith (4) and 5. Quantum (3) after those three lines.
    • Ratings {3, 3, 3, 3, 3} with k = 3 print TechPro, MegaCorp and Quantum, each with rating 3.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free