Start learning free

LESSON 256 OF 285 · NESTED LOOPS

Top K Brands V6 in Go: Tie-Break by Review Count

Practice Read the full explanation

Rank the top k brands by rating, breaking ties with the review count. This builds on v4's repeated search (not on v5: there is no filtering here); only the comparison gets a second criterion.

You start with:

brands := []string{"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"}
ratings := []int{4, 5, 5, 3, 4}
reviews := []int{200, 150, 500, 100, 300}
k := 3

Build:

1. NeoByte (5, 500)
2. MegaCorp (5, 150)
3. Zenith (4, 300)

Rules:

  • Rating decides first: the higher rating wins.
  • If two brands have the same rating, the one with more reviews wins.
  • If rating and reviews are both equal, the one listed first wins (the test data has no such pair, but your code must follow the rule).
  • k is never larger than the number of brands.
  • Each line is "rank. Brand (rating, reviews)", starting at rank 1.
  • Print the lines, one per line, with fmt.Println(...).

Start from v4: the same used := make([]bool, len(ratings)) and lines := []string{}, the same two loops. Only the comparison inside the inner loop changes.

Use a chain (if / else if / else if): no candidate yet, take this one; else a higher rating, take this one; else the same rating and more reviews, take this one.

brands := []string{"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"}
ratings := []int{4, 5, 5, 3, 4}
reviews := []int{200, 150, 500, 100, 300}
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 {
                bestIndex = i
            } else if ratings[i] > ratings[bestIndex] {
                bestIndex = i
            } else if ratings[i] == ratings[bestIndex] && reviews[i] > reviews[bestIndex] {
                bestIndex = i
            }
        }
    }
    used[bestIndex] = true
    lines = append(lines, strconv.Itoa(rank) + ". " + brands[bestIndex] + " (" + strconv.Itoa(ratings[bestIndex]) + ", " + strconv.Itoa(reviews[bestIndex]) + ")")
}
fmt.Println(strings.Join(lines, "\n"))

STEP 1 OF 12
    Ctrl + Enter to check

    GO · NESTED LOOPS

    Top K Brands V6 in Go, explained

    Problem overview

    Version 6 keeps the top k ranking of version 4 and adds a second criterion. The rating still decides first, but when two brands have the same rating, the one with more reviews ranks higher. The data has a third parallel slice, reviews:

    brands := []string{"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"}
    ratings := []int{4, 5, 5, 3, 4}
    reviews := []int{200, 150, 500, 100, 300}
    k := 3
    

    If the rating and the review count are both equal, the brand listed first wins. The value of k is never larger than the number of brands. Each line is rank. Brand (rating, reviews):

    1. NeoByte (5, 500)
    2. MegaCorp (5, 150)
    3. Zenith (4, 300)
    

    MegaCorp and NeoByte both have 5, and NeoByte's 500 reviews put it first. TechPro and Zenith both have 4, and Zenith's 300 reviews beat TechPro's 200.

    Approach: the same rounds, a two-level comparison

    The structure is the repeated search from version 4: k rounds, a used flag per brand, and bestIndex starting at -1 in every round. Only the question "does brand i beat the best so far?" changes. It now has three cases, tested in order:

    1. Nothing is found yet (bestIndex == -1): this brand is the best so far.
    2. Its rating is higher than the best one's: it wins, whatever the reviews.
    3. The ratings are equal and it has more reviews: it wins the tie.

    If none of the cases holds, the current best stays. That covers a lower rating, an equal rating with fewer or equal reviews, and so a complete tie keeps the earlier brand, as the rules require. Using else if keeps the cases exclusive, so a higher rating is settled before the reviews are even looked at.

    The three rounds on the starting data:

    1. Round 1: TechPro (4, 200) is found first. MegaCorp's 5 beats it. NeoByte has the same 5 as MegaCorp, but 500 reviews against 150, so it takes over. Quantum and Zenith have lower ratings. NeoByte wins.
    2. Round 2: NeoByte is skipped. MegaCorp's 5 beats TechPro's 4 and nothing later beats MegaCorp, so MegaCorp wins.
    3. Round 3: TechPro (4, 200) is found first, and Zenith has the same rating with 300 reviews, so Zenith wins.

    Step by step

    1. Create used, a make([]bool, len(ratings)) with every slot false.
    2. Create lines, an empty []string.
    3. Write the rounds loop, for rank := 1; rank <= k; rank++ {. The counter is also the printed rank.
    4. Set bestIndex := -1.
    5. Write the inner loop for i := range ratings {.
    6. Skip used brands with if !used[i] {.
    7. First case: if bestIndex == -1 {, set bestIndex = i.
    8. Second case: else if ratings[i] > ratings[bestIndex], set bestIndex = i.
    9. Third case: else if the ratings are equal and reviews[i] > reviews[bestIndex], set bestIndex = i.
    10. Mark the winner after the inner loop: used[bestIndex] = true.
    11. Add the line with append: rank, ". ", brand, then the rating and the review count in parentheses separated by ", ". Every number goes through strconv.Itoa.
    12. Print after the loop, with the lines joined by newlines.

    The solution in Go

    brands := []string{"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"}
    ratings := []int{4, 5, 5, 3, 4}
    reviews := []int{200, 150, 500, 100, 300}
    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 {
                    bestIndex = i
                } else if ratings[i] > ratings[bestIndex] {
                    bestIndex = i
                } else if ratings[i] == ratings[bestIndex] && reviews[i] > reviews[bestIndex] {
                    bestIndex = i
                }
            }
        }
        used[bestIndex] = true
        lines = append(lines, strconv.Itoa(rank) + ". " + brands[bestIndex] + " (" + strconv.Itoa(ratings[bestIndex]) + ", " + strconv.Itoa(reviews[bestIndex]) + ")")
    }
    fmt.Println(strings.Join(lines, "\n"))
    

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

    • else if chains. Go evaluates the conditions top to bottom and runs only the first block whose condition is true. The else must start on the same line as the closing brace.
    • && short-circuits. In the third case, the review comparison is evaluated only when the ratings are equal.
    • Indexes are safe here. The second and third cases read ratings[bestIndex] only after the first case has handled bestIndex == -1, so index -1 is never read. If the first test was missing, the code would panic in the first round.
    • Several slices, one index. brands, ratings and reviews are linked only by position. Nothing in Go checks that they have the same length.
    • Numbers into text. + joins only strings, so both the rank and the two numbers in parentheses use strconv.Itoa. The ", " between rating and reviews is part of a string literal.

    Complexity

    Time is O(k * n): k rounds scan the n brands, and each comparison takes constant time. Space is O(n + k), for the flags and the output lines.

    Edge cases and common mistakes

    • Reviews before rating. Comparing reviews first would put a brand with a low rating and many reviews on top. With ratings 3, 5, 4, 1, 2 and reviews 9000, 1, 500, 99999, 7, the right order starts with the brand rated 5 (1 review), not the one with 99999 reviews.
    • Dropping the equal-rating test. The third case needs ratings[i] == ratings[bestIndex]. Without it, a lower-rated brand with more reviews would replace the best.
    • Using >= for reviews. A brand with the same rating and the same number of reviews would replace the earlier one. With every rating 5 and every review count 10, the correct output is TechPro, MegaCorp, NeoByte in listed order.
    • Ties on reviews as well. With ratings all 5 and reviews 10, 30, 20, 30 and 5, the order is MegaCorp (30), Quantum (30), NeoByte (20), TechPro (10) and Zenith (5): the two brands with 30 reviews keep their listed order.
    • Forgetting to mark the winner. Without used[bestIndex] = true, all the rounds would find NeoByte.
    • Printing the wrong format. The line has a comma and a space between the rating and the review count: (5, 500).

    Testing

    • The starting data with k = 3 prints NeoByte (5, 500), MegaCorp (5, 150) and Zenith (4, 300).
    • The same data with k = 5 adds 4. TechPro (4, 200) and 5. Quantum (3, 100).
    • All ratings 5 with reviews 10, 10, 10, 10, 10 and k = 3 print TechPro, MegaCorp and NeoByte.
    • Ratings 3, 5, 4, 1, 2 with reviews 9000, 1, 500, 99999, 7 and k = 3 print MegaCorp (5, 1), NeoByte (4, 500) and TechPro (3, 9000).
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free