Start learning free

LESSON 187 OF 285 · LOOPING OVER ARRAY INDICES

Top K Brands V3 in Go: Finding the Best Rating with a Loop

Practice Read the full explanation

Many brands sell the same product, stored in two parallel slices: ratings[i] is the rating of brands[i]. Find the highest-rated brand by scanning with a loop.

You start with:

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

Build:

1. MegaCorp (5)

Rules:

  • Keep the position of the best brand so far in bestIndex, starting at 0, and scan the positions from 1 to the end with a loop.
  • Update bestIndex only on a strictly higher rating. If two brands share the top rating, the one listed first wins (MegaCorp at position 1, not NeoByte at position 3).
  • Format the winner as "1. Brand (rating)" and print it with fmt.Println(...).

Walk the positions with for i := 1; i < len(ratings); i++ { and compare each rating with the best one so far.

Go needs strconv.Itoa(...) to turn an int into text before joining it with +.

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

bestIndex := 0
for i := 1; i < len(ratings); i++ {
    if ratings[i] > ratings[bestIndex] {
        bestIndex = i
    }
}
fmt.Println("1. " + brands[bestIndex] + " (" + strconv.Itoa(ratings[bestIndex]) + ")")

STEP 1 OF 5
    Ctrl + Enter to check

    GO · LOOPING OVER ARRAY INDICES

    Top K Brands V3 in Go, explained

    Problem overview

    Version 3 of the Top K Brands project works with any number of brands. They are stored in two parallel slices: brands[i] is a brand and ratings[i] is its rating. The starter data is:

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

    The program prints the highest-rated brand as 1. Brand (rating). Two brands share the top rating of 5, MegaCorp at position 1 and NeoByte at position 3, and the one listed first wins:

    1. MegaCorp (5)
    

    Approach: remember the position of the best so far

    For a list, a loop works: keep the best brand found so far, and compare each new brand with it. The lesson keeps the position of the best brand in bestIndex, not its rating, because one position gives access to both the name and the rating through the two slices.

    The variable starts at 0, since the first brand is the best of the brands seen so far. The loop then looks at positions 1, 2, 3 and so on. A brand replaces the current best only when its rating is strictly higher, so on a tie the earlier brand keeps the lead. That is how MegaCorp stays ahead of NeoByte.

    Walking through the data: bestIndex starts at 0 (rating 4). Position 1 has 5 > 4, so bestIndex becomes 1. Position 2 has 3, no change. Position 3 has 5, which is not greater than 5, no change. Position 4 has 4, no change. The loop ends with bestIndex equal to 1.

    Step by step

    1. Create bestIndex and set it to 0.
    2. Write the loop with for i := 1; i < len(ratings); i++ {. It starts at 1 because position 0 is already the best so far. Close the brace at once so the next steps go inside.
    3. Compare inside the loop: if ratings[i] > ratings[bestIndex] {. Strictly greater.
    4. Update inside the if: bestIndex = i.
    5. Print after the loop, reading brands[bestIndex] and ratings[bestIndex]. The rating goes through strconv.Itoa so that + can join it to the strings.

    The solution in Go

    brands := []string{"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"}
    ratings := []int{4, 5, 3, 5, 4}
    
    bestIndex := 0
    for i := 1; i < len(ratings); i++ {
        if ratings[i] > ratings[bestIndex] {
            bestIndex = i
        }
    }
    fmt.Println("1. " + brands[bestIndex] + " (" + strconv.Itoa(ratings[bestIndex]) + ")")
    

    The code uses the fmt and strconv packages.

    The details worth knowing

    • Go has one loop keyword. for init; condition; post { } is the classic counting loop. There is no while, and no parentheses around the three parts.
    • len gives the length. len(ratings) is 5, and valid positions are 0 to 4. The condition i < len(ratings) stops after position 4.
    • Indexing out of range panics. Reading ratings[5] stops the program with index out of range at run time.
    • Slices of the same length. The code assumes brands and ratings have the same length. Nothing in Go checks that for you.

    Complexity

    Time is O(n): the loop visits each of the other n - 1 positions once and does constant work per position. Extra space is O(1), because only bestIndex and i are added.

    Edge cases and common mistakes

    • Ties. With >= in the comparison, bestIndex would move to NeoByte at position 3 and the output would be 1. NeoByte (5). The lesson's tests expect the first brand with the top rating.
    • An empty slice. With no brands, ratings[bestIndex] reads position 0 of an empty slice and panics with index out of range [0] with length 0. The lesson's data always has brands.
    • Storing the rating instead of the position. Then the brand's name cannot be found again without a second search.
    • Looping to len(ratings) inclusive. i <= len(ratings) reads one position too far and panics.
    • Starting the loop at 0. It still gives the right answer, since an element is never strictly greater than itself, but it makes one useless comparison.

    Testing

    • Ratings {4, 5, 3, 5, 4} give MegaCorp (5).
    • Ratings {5, 4, 3, 2, 1} give TechPro (5), where the best is already first.
    • Ratings {1, 2, 3, 4, 5} give Zenith (5), the last position.
    • Ratings {3, 3, 3, 3, 3} give TechPro (3), the first.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free