Start learning free

LESSON 258 OF 293 · NESTED LOOPS

Top K Brands V5 in Rust: Filter by Product, Then Rank

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: an empty editor (no starter code). Declare this data yourself:

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;

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 println!(...).

Build filtered_brands and filtered_ratings 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 (found stays false): add a line only when a brand was found.

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"));

STEP 1 OF 25
    Ctrl + Enter to check

    RUST · NESTED LOOPS

    Top K Brands V5 in Rust, explained

    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

    1. Create products with Laptop, Phone, Laptop, Tablet, Phone and Laptop.
    2. Create brands with TechPro, MegaCorp, NeoByte, Quantum, Zenith and AlphaTech, in the same row order.
    3. Create ratings as 4, 5, 5, 3, 4 and 4.
    4. Create target as "Laptop".
    5. Create k as 2.
    6. Create filtered_brands as an empty vector with Vec::new(), using let mut.
    7. Create filtered_ratings the same way.
    8. Loop over the rows with for i in 0..products.len().
    9. Test the row with an if that checks whether products[i] == target.
    10. Copy the brand into filtered_brands with push.
    11. Copy the rating into filtered_ratings in the same way, so both vectors keep the same positions.
    12. Create used after the loop, with one false for each filtered rating.
    13. Create lines as an empty vector.
    14. Loop over the ranks with for rank in 1..=k.
    15. Create best_index inside the loop, starting at 0.
    16. Create found inside the loop, starting at false.
    17. Open the inner loop over every position i of filtered_ratings.
    18. Skip used entries with an if on !used[i].
    19. Test for a new best: nothing found yet, or a strictly higher rating than the best one's.
    20. Set best_index to i.
    21. Set found to true.
    22. After the inner loop, open an if found block, so a round with no candidate does nothing.
    23. Mark the winner by setting used[best_index] to true.
    24. Add the line to lines with push and format!, in the form rank, dot, space, brand, and the rating in parentheses.
    25. 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. So filtered_brands.push(brands[i]) compiles without clone(), and the vector becomes a Vec<&str>.
    • Comparing text. products[i] == target compares the contents of two &str values, 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 first push calls.
    • The guard on found. When nobody is found, best_index is still 0, which would be an out-of-range index for an empty filtered list. The if found block 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 with k = 3, all three laptops are listed: NeoByte (5), TechPro (4) and AlphaTech (4). With k = 5 the output is the same three lines.
    • Exactly one match. Tablet with k = 2 prints only 1. Quantum (3).
    • No matches. Watch with k = 2 prints an empty line, with no error. So does "laptop" in lower case, because the comparison is case-sensitive.
    • Another product. Phone with k = 2 prints 1. MegaCorp (5) and 2. 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 ratings in the ranking loop would rank brands that sell other products. The loop and the used flags must work on the filtered vectors.
    • Making used too 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) prints 1. NeoByte (5) and 2. TechPro (4).
    • Laptop with k = 3 adds 3. AlphaTech (4).
    • Phone with k = 2 prints 1. MegaCorp (5) and 2. Zenith (4).
    • Tablet with k = 2 prints 1. Quantum (3).
    • Watch prints an empty line.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free