Start learning free

LESSON 255 OF 285 · NESTED LOOPS

Top K Brands V5 in Go: Filtering Parallel Slices by Product

Practice Read the full explanation

The full catalog covers many products. Filter to one product first, then rank the top k brands that sell it, using v4's repeated search on the filtered lists.

You start with:

products := []string{"Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"}
brands := []string{"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"}
ratings := []int{4, 5, 5, 3, 4, 4}
target := "Laptop"
k := 2

Build:

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

Rules:

  • Filter: copy the brand and the rating of every row whose product equals target into two new lists, keeping the order.
  • From the filtered lists pick the top k by rating, highest first, with v4's repeated search. Ties go to the entry listed first.
  • If fewer than k products match, list only those that exist: when no brand is left, add no more lines (no extra lines, no error).
  • Each line is "rank. Brand (rating)", starting at rank 1.
  • Print the lines, one per line, with fmt.Println(...).

Build filteredBrands and filteredRatings first: a loop over the catalog that copies the row when products[i] == target.

Then run v4's repeated search over the filtered lists (same code, new names).

If fewer than k products match, some round finds nobody (bestIndex stays -1): add a line only when a brand was found.

products := []string{"Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"}
brands := []string{"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"}
ratings := []int{4, 5, 5, 3, 4, 4}
target := "Laptop"
k := 2

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

STEP 1 OF 18
    Ctrl + Enter to check

    GO · NESTED LOOPS

    Top K Brands V5 in Go, explained

    Problem overview

    The catalog in version 5 covers several products. Each row has a product, a brand and a rating, stored in three parallel slices, and the program must rank the top k brands that sell one chosen product:

    products := []string{"Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"}
    brands := []string{"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"}
    ratings := []int{4, 5, 5, 3, 4, 4}
    target := "Laptop"
    k := 2
    

    Only the Laptop rows count: TechPro (4), NeoByte (5) and AlphaTech (4). The best two are NeoByte and then TechPro, which is listed before AlphaTech and so wins the tie at 4. The output lines are rank. Brand (rating):

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

    If fewer than k brands match, the program lists only the ones that exist, with no error and no extra lines.

    Approach: filter first, then reuse the repeated search

    The work splits into two independent parts. The first is a filter: walk the catalog and copy the brand and the rating of every row whose product equals target into two new slices, in the original order. The second part is the version 4 search, run on those filtered slices instead of the full ones. That search runs k rounds, skips the brands already used, and picks the highest rating, replacing the best only on a strictly higher rating.

    For the starting data the filtered slices are [TechPro NeoByte AlphaTech] and [4 5 4]. The brand and the rating at the same position still belong together, because they were appended in the same order. Round 1 picks NeoByte (5). In round 2, TechPro (4) is found first and AlphaTech's 4 doesn't beat it.

    There is one change from version 4. The number of matches can be smaller than k, so a round may find nobody. The search then leaves bestIndex at -1, and the program must not use it as an index. A check protects the code that marks the winner and adds the line.

    Step by step

    1. Create filteredBrands, an empty []string.
    2. Create filteredRatings, an empty []int. The two slices will stay in step.
    3. Loop over the catalog rows with for i := 0; i < len(products); i++ {. Close the brace right away.
    4. Test the product with if products[i] == target {.
    5. Append the brand of row i to filteredBrands.
    6. Append the rating of row i to filteredRatings, in the same order.
    7. Create used, a []bool with one slot per filtered rating. It is as long as the filtered slices, not the catalog.
    8. Create lines, an empty []string.
    9. Write the rounds loop for rank := 1; rank <= k; rank++ {.
    10. Set bestIndex := -1 at the start of each round.
    11. Write the inner loop over the positions of filteredRatings.
    12. Skip used entries with if !used[i] {.
    13. Test for a better one: bestIndex == -1 or a strictly higher rating than the best so far.
    14. Remember it: bestIndex = i.
    15. Check that one was found after the inner loop with if bestIndex != -1 {.
    16. Mark the winner with used[bestIndex] = true.
    17. Add the line with append: the rank, a dot and a space, the brand, and the rating in parentheses, with strconv.Itoa for both numbers.
    18. Print after the loop, with the lines joined by newlines.

    The solution in Go

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

    The code uses the fmt, strconv and strings packages. The Go details to keep in mind:

    • Strings compare with ==. products[i] == target compares the contents, and it is case-sensitive: "laptop" doesn't match "Laptop".
    • append must be assigned back. filteredBrands = append(filteredBrands, brands[i]) keeps the result, which can be a new slice.
    • Start from empty slices. []string{} and []int{} have length 0, so they grow only by the rows that match.
    • Size by the filtered slice. used is made after the filter, with len(filteredRatings). Using len(ratings) would still work, but the extra slots would never be read.
    • An empty lines prints an empty line. strings.Join of no elements is "", and fmt.Println prints it with a line break.

    Complexity

    With n catalog rows and m matches, the filter costs O(n) and the search costs O(k * m), because each of the k rounds scans the m filtered entries. The total is O(n + k * m). The extra space is O(m + k) for the filtered slices, the flags and the lines.

    Edge cases and common mistakes

    • Fewer than k matches. With the starting data and k = 5, only three Laptop rows exist, so the output is NeoByte (5), TechPro (4) and AlphaTech (4). Without the bestIndex != -1 check, the fourth round would use index -1 and panic.
    • No matches. For a product such as "Camera", the filtered slices are empty, no round finds anything, and the program prints an empty line. A case mismatch, such as "laptop", behaves the same way.
    • A single match. Tablet has one row, so with k = 2 the output is only 1. Quantum (3).
    • Searching the full ratings. If the search loops over ratings instead of filteredRatings, brands from other products (such as MegaCorp, a Phone) appear in the result.
    • Breaking the pairing. Appending the brand and the rating in different orders, or to different conditions, makes a brand's name and rating point at different rows. Keep both appends under the same if.
    • Ties. TechPro and AlphaTech both have 4. The strict > keeps TechPro, which is listed first, ahead of AlphaTech.

    Testing

    • Target "Laptop" with k = 2 prints 1. NeoByte (5) and 2. TechPro (4).
    • Target "Laptop" with k = 3 adds 3. AlphaTech (4).
    • Target "Phone" with k = 2 prints 1. MegaCorp (5) and 2. Zenith (4).
    • Target "Tablet" with k = 2 prints only 1. Quantum (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