Problem overview
A catalog has six rows. Row i says that brands[i] sells products[i] with ratings[i]. The program is given a target product and a number k, and it prints the top k brands that sell that product, as rank. Brand (rating).
With the target "Laptop" and k = 2, three rows match: TechPro (4), NeoByte (5) and AlphaTech (4). The two best are:
1. NeoByte (5)
2. TechPro (4)
Ties go to the entry listed first, so TechPro comes before AlphaTech. If fewer than k rows match, the program lists only the ones that exist, with no extra lines and no error.
The previous version ranked a whole list of brands with a repeated search. This version adds a filtering step in front and runs the same search on the filtered lists.
Approach: filter, then repeat the search
The work splits into two parts. First, the program copies the brand and the rating of every row whose product equals target into two new vectors, filtered_brands and filtered_ratings. The rows are visited in order, so the copies keep the original order, and the two new vectors stay lined up by position.
Second, it runs the repeated search on the filtered data. A vector of flags, used, has one false per filtered row. Each round picks the unused entry with the highest rating, replacing the current best only on a strictly higher rating so that ties go to the earlier entry, and then flips that entry's flag.
The new requirement is a round that finds nobody. If only two laptops exist and k is 3, the third round has no candidates. A flag, found, records whether the round picked anything, and the code that marks a winner and adds a line is guarded by it. A round without a winner adds no line.
Step by step
- Create
productswith Laptop, Phone, Laptop, Tablet, Phone and Laptop. - Create
brandswith TechPro, MegaCorp, NeoByte, Quantum, Zenith and AlphaTech, in the same row order. - Create
ratingsas 4, 5, 5, 3, 4 and 4. - Create
targetas"Laptop". - Create
kas 2. - Create
filtered_brandsas an empty vector withVec::new(), usinglet mut. - Create
filtered_ratingsthe same way. - Loop over the rows with
for i in 0..products.len(). - Test the row with an
ifthat checks whetherproducts[i] == target. - Copy the brand into
filtered_brandswithpush. - Copy the rating into
filtered_ratingsin the same way, so both vectors keep the same positions. - Create
usedafter the loop, with onefalsefor each filtered rating. - Create
linesas an empty vector. - Loop over the ranks with
for rank in 1..=k. - Create
best_indexinside the loop, starting at 0. - Create
foundinside the loop, starting atfalse. - Open the inner loop over every position
ioffiltered_ratings. - Skip used entries with an
ifon!used[i]. - Test for a new best: nothing found yet, or a strictly higher rating than the best one's.
- Set
best_indextoi. - Set
foundtotrue. - After the inner loop, open an
if foundblock, so a round with no candidate does nothing. - Mark the winner by setting
used[best_index]totrue. - Add the line to
lineswithpushandformat!, in the form rank, dot, space, brand, and the rating in parentheses. - Print after the loop with
lines.join("\n").
The solution in Rust
let products = vec!["Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"];
let brands = vec!["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"];
let ratings = vec![4, 5, 5, 3, 4, 4];
let target = "Laptop";
let k = 2;
let mut filtered_brands = Vec::new();
let mut filtered_ratings = Vec::new();
for i in 0..products.len() {
if products[i] == target {
filtered_brands.push(brands[i]);
filtered_ratings.push(ratings[i]);
}
}
let mut used = vec![false; filtered_ratings.len()];
let mut lines = Vec::new();
for rank in 1..=k {
let mut best_index = 0;
let mut found = false;
for i in 0..filtered_ratings.len() {
if !used[i] {
if !found || filtered_ratings[i] > filtered_ratings[best_index] {
best_index = i;
found = true;
}
}
}
if found {
used[best_index] = true;
lines.push(format!("{}. {} ({})", rank, filtered_brands[best_index], filtered_ratings[best_index]));
}
}
println!("{}", lines.join("\n"));
Rust details worth knowing:
- Copying strings is cheap here.
brands[i]is a&str, a shared reference to text, which Rust copies freely. Sofiltered_brands.push(brands[i])compiles withoutclone(), and the vector becomes aVec<&str>. - Comparing text.
products[i] == targetcompares the contents of two&strvalues, and the match is case-sensitive:"laptop"matches no row. - Types are inferred. The two filtered vectors start as
Vec::new()and take their element types from the firstpushcalls. - The guard on
found. When nobody is found,best_indexis still 0, which would be an out-of-range index for an empty filtered list. Theif foundblock keeps the code from using it. - An empty result prints an empty line. Joining an empty vector gives an empty string, so
println!prints a blank line. A target that matches no row, such as"Watch", gives exactly that.
Complexity
Time: O(n + k * m), where n is the number of rows and m the number of matching rows. The filter scans all n rows once. Each of the k rounds then scans the m filtered entries. Space: O(m + k) for the filtered vectors, the flags and the output lines.
Edge cases and common mistakes
- Fewer matches than
k. For Laptop withk = 3, all three laptops are listed: NeoByte (5), TechPro (4) and AlphaTech (4). Withk = 5the output is the same three lines. - Exactly one match. Tablet with
k = 2prints only1. Quantum (3). - No matches. Watch with
k = 2prints an empty line, with no error. So does"laptop"in lower case, because the comparison is case-sensitive. - Another product. Phone with
k = 2prints1. MegaCorp (5)and2. Zenith (4). - Ties. TechPro and AlphaTech both have rating 4. TechPro was added to the filtered list first, so it wins the second place.
- Searching the original lists. Using
ratingsin the ranking loop would rank brands that sell other products. The loop and theusedflags must work on the filtered vectors. - Making
usedtoo early. It must be as long as the filtered list, so it is created after the filter loop, not before.
Testing
- The lesson's data (Laptop,
k = 2) prints1. NeoByte (5)and2. TechPro (4). - Laptop with
k = 3adds3. AlphaTech (4). - Phone with
k = 2prints1. MegaCorp (5)and2. Zenith (4). - Tablet with
k = 2prints1. Quantum (3). - Watch prints an empty line.
