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
- Create
filteredBrands, an empty[]string. - Create
filteredRatings, an empty[]int. The two slices will stay in step. - Loop over the catalog rows with
for i := 0; i < len(products); i++ {. Close the brace right away. - Test the product with
if products[i] == target {. - Append the brand of row
itofilteredBrands. - Append the rating of row
itofilteredRatings, in the same order. - Create
used, a[]boolwith one slot per filtered rating. It is as long as the filtered slices, not the catalog. - Create
lines, an empty[]string. - Write the rounds loop
for rank := 1; rank <= k; rank++ {. - Set
bestIndex := -1at the start of each round. - Write the inner loop over the positions of
filteredRatings. - Skip used entries with
if !used[i] {. - Test for a better one:
bestIndex == -1or a strictly higher rating than the best so far. - Remember it:
bestIndex = i. - Check that one was found after the inner loop with
if bestIndex != -1 {. - Mark the winner with
used[bestIndex] = true. - Add the line with
append: the rank, a dot and a space, the brand, and the rating in parentheses, withstrconv.Itoafor both numbers. - 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] == targetcompares the contents, and it is case-sensitive:"laptop"doesn't match"Laptop". appendmust 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.
usedis made after the filter, withlen(filteredRatings). Usinglen(ratings)would still work, but the extra slots would never be read. - An empty
linesprints an empty line.strings.Joinof no elements is"", andfmt.Printlnprints 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
kmatches. With the starting data andk = 5, only three Laptop rows exist, so the output is NeoByte (5), TechPro (4) and AlphaTech (4). Without thebestIndex != -1check, 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 = 2the output is only1. Quantum (3). - Searching the full ratings. If the search loops over
ratingsinstead offilteredRatings, 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"withk = 2prints1. NeoByte (5)and2. TechPro (4). - Target
"Laptop"withk = 3adds3. AlphaTech (4). - Target
"Phone"withk = 2prints1. MegaCorp (5)and2. Zenith (4). - Target
"Tablet"withk = 2prints only1. Quantum (3).
