Problem overview
The catalog is now a list of rows spread over three parallel arrays: products, brands and ratings. Row i says that the brand brands[i] sells the product products[i] with the rating ratings[i]. A variable target names one product and k says how many brands to show.
The program first keeps only the rows of the target product, then ranks the top k brands among them by rating, highest first. Ties go to the entry listed first. Each line has the form rank. Brand (rating), starting at rank 1. With target = "Laptop" and k = 2 the output is:
1. NeoByte (5)
2. TechPro (4)
If fewer than k rows match, the program lists only the ones that exist, with no extra lines and no error.
Approach: two stages
The work splits into two independent stages. The first is a filter: walk through every row and copy the brand and rating of each row whose product equals target into two new arrays, keeping the order. The second is the repeated search from the previous version, run on the filtered arrays instead of the full ones: find the best entry that isn't taken yet, mark it taken, and repeat k times.
Because the filter keeps the order, the tie rule still works: among equal ratings, the entry that comes first in the catalog comes first in the filtered arrays. The filtered brand and rating arrays always have the same length, and a brand and its rating sit at the same position in both.
The only new risk is in the second stage. The filtered lists can be shorter than k, so a round may find nothing. The round must check for that before using its result.
The filter on the starter data
The rows for "Laptop" are at positions 0, 2 and 5. After the filter, filteredBrands is ["TechPro", "NeoByte", "AlphaTech"] and filteredRatings is [4, 5, 4]. Round 1 picks NeoByte (5). Round 2 has TechPro and AlphaTech, both rated 4, and the one listed first, TechPro, wins.
Step by step
- Create
filteredBrandsas an empty[String]andfilteredRatingsas an empty[Int]. - Loop over the rows with
for index in products.indices. - Keep the matching rows. If
products[index] == target, appendbrands[index]to one array andratings[index]to the other, in the same order. - Create
usedwith onefalseper filtered rating. It must be as long as the filtered lists, not the full catalog. - Create
linesas an empty[String]. - Loop over the ranks with
for rank in 1...k, and start each round withvar bestIndex = -1. - Scan the filtered ratings. For each index that isn't used, take it if nothing is chosen yet or its rating is strictly higher than the best one's.
- Check that something was found with
bestIndex != -1, because a round may have nobody left. - Inside the check, set
used[bestIndex]totrueand append the formatted line tolines. - Print the lines joined with
"\n".
The solution in Swift
let products = ["Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"]
let brands = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"]
let ratings = [4, 5, 5, 3, 4, 4]
let target = "Laptop"
let k = 2
var filteredBrands = [String]()
var filteredRatings = [Int]()
for index in products.indices {
if products[index] == target {
filteredBrands.append(brands[index])
filteredRatings.append(ratings[index])
}
}
var used = Array(repeating: false, count: filteredRatings.count)
var lines = [String]()
for rank in 1...k {
var bestIndex = -1
for index in filteredRatings.indices {
if !used[index] {
if bestIndex == -1 || filteredRatings[index] > filteredRatings[bestIndex] {
bestIndex = index
}
}
}
if bestIndex != -1 {
used[bestIndex] = true
lines.append("\(rank). \(filteredBrands[bestIndex]) (\(filteredRatings[bestIndex]))")
}
}
print(lines.joined(separator: "\n"))
Swift specifics worth knowing:
==compares strings by content.products[index] == targetis true when the two strings have the same characters. Case matters:"laptop"does not equal"Laptop".- Empty arrays with a type.
[String]()and[Int]()create empty arrays whose element types are fixed, soappendaccepts only the right kind of value. indicesof the filtered array. The scan usesfilteredRatings.indices, the positions of the filtered list. Usingratings.indicesthere would index the filtered arrays with positions that may not exist.1...kwith a short list. The loop always runsktimes. ThebestIndex != -1check is what keeps the rounds without a winner silent.- Printing an empty array's lines. If nothing matches,
linesis empty,joinedgives an empty string, andprintoutputs a single blank line.
Edge cases and common mistakes
- Fewer matches than
k. Withtarget = "Phone"andk = 3only two rows match, so the output is1. MegaCorp (5)and2. Zenith (4), with no third line. With"Tablet"andk = 2the output is only1. Quantum (3). - No match at all. With
target = "Watch", or"laptop"in lower case, the filtered lists are empty and the program prints just an empty line. - Ranking before filtering. If you rank the whole catalog first, brands of other products take places in the top
k. The filter has to come first. - Sizing
usedfrom the full catalog. It would have extra flags that no filtered entry owns, which doesn't crash but is wrong in principle. Size it from the filtered arrays. - Skipping the
bestIndexcheck. Without it,used[-1]crashes the program as soon askexceeds the number of matches. - Ties. With
target = "Laptop"andk = 3, TechPro and AlphaTech both have a 4, and the output keeps catalog order: NeoByte, TechPro, AlphaTech.
Testing
These outputs come from the solution on the starter catalog.
| target | k | output |
|---|---|---|
"Laptop" | 3 | 1. NeoByte (5), 2. TechPro (4), 3. AlphaTech (4) |
"Laptop" | 5 | the same three lines |
"Phone" | 1 | 1. MegaCorp (5) |
"Phone" | 3 | 1. MegaCorp (5), 2. Zenith (4) |
"Watch" | 2 | a blank line |
Try these in the editor above by changing target and k.
