Start learning free

LESSON 257 OF 293 · NESTED LOOPS

Top K Brands V4 in Rust: Repeated Search for the Top K

Practice Read the full explanation

Show the top k brands by rating. This is v3's search, repeated k times: find the best brand, mark it as taken, then search again among the brands that are not taken yet, until you have k brands in rank order.

You start with: an empty editor (no starter code). Declare this data yourself:

let brands = vec!["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
let ratings = vec![4, 5, 3, 5, 4];
let k = 3;

Build:

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

Rules:

  • Repeat v3's search k times. Each round looks only at brands that are not taken yet and picks the one with the highest rating, then marks it as taken (one true/false flag per brand).
  • Ties go to the brand listed first: keep the first brand you find and replace it only on a strictly higher rating.
  • k is never larger than the number of brands.
  • Each line is "rank. Brand (rating)", starting at rank 1.
  • Print the lines, one per line, with println!(...).

Start with the two declarations let mut used = vec![false; ratings.len()]; and let mut lines = Vec::new();. A flag tells whether that position is already taken.

Each round is v3's search: nothing found yet, scan every position, skip taken ones, keep the first candidate and replace it only on a strictly higher rating. Then mark the winner as taken and add its line.

let brands = vec!["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
let ratings = vec![4, 5, 3, 5, 4];
let k = 3;
let mut used = vec![false; 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..ratings.len() {
        if !used[i] {
            if !found || ratings[i] > ratings[best_index] {
                best_index = i;
                found = true;
            }
        }
    }
    used[best_index] = true;
    lines.push(format!("{}. {} ({})", rank, brands[best_index], ratings[best_index]));
}
println!("{}", lines.join("\n"));

STEP 1 OF 16
    Ctrl + Enter to check

    RUST · NESTED LOOPS

    Top K Brands V4 in Rust, explained

    Problem overview

    Five brands have ratings: TechPro 4, MegaCorp 5, Quantum 3, NeoByte 5 and Zenith 4. The program prints the top k brands in rank order, here with k = 3, one per line as rank. Brand (rating):

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

    Ties go to the brand listed first, so MegaCorp precedes NeoByte, and TechPro precedes Zenith. The input guarantees that k is never larger than the number of brands.

    The previous version found the single best brand with one scan. This version repeats that scan k times, setting each winner aside so the next round finds the next best.

    Approach: search, mark, search again

    The program keeps one flag per brand in a vector used, all false at the start. A round looks only at brands whose flag is false and picks the one with the highest rating. It then flips the winner's flag to true, so the following rounds skip it.

    Within a round, the search keeps the position of the best brand so far in best_index. A second variable, found, says whether the round has picked anything yet. Without it, starting best_index at 0 would be wrong when brand 0 is already taken: the loop would compare against a used brand. In some languages a position of -1 means "none", but a Rust index can't be negative, so a flag does the job.

    A brand replaces the current best only when its rating is strictly higher. A tie keeps the earlier brand, which is the rule. Each finished round adds one text line to a vector, and a final join prints them all.

    Step by step

    1. Create brands with the five names, in the given order.
    2. Create ratings as 4, 5, 3, 5, 4, so each rating lines up with its brand.
    3. Create k as 3.
    4. Create used with vec![false; ratings.len()], using let mut.
    5. Create lines as an empty vector with Vec::new(), also let mut.
    6. Loop over the ranks with for rank in 1..=k. The range includes k, so rank is 1, 2 and 3, and it is also the number printed in front of the brand.
    7. Create best_index inside the loop, starting at 0, so every round starts fresh.
    8. Create found inside the loop, starting at false.
    9. Open the inner loop over every position i of ratings.
    10. Skip taken brands with an if that is true when used[i] is false.
    11. Test for a new best with a second if: nothing found yet, or a strictly higher rating than the best one's.
    12. Remember the brand by setting best_index to i.
    13. Record the find by setting found to true.
    14. After the inner loop, set used[best_index] to true.
    15. Add the round's line to lines with push and format!: the rank, a dot and a space, the brand, and the rating in parentheses.
    16. Print after the loop with lines.join("\n") inside println!.

    The solution in Rust

    let brands = vec!["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
    let ratings = vec![4, 5, 3, 5, 4];
    let k = 3;
    let mut used = vec![false; 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..ratings.len() {
            if !used[i] {
                if !found || ratings[i] > ratings[best_index] {
                    best_index = i;
                    found = true;
                }
            }
        }
        used[best_index] = true;
        lines.push(format!("{}. {} ({})", rank, brands[best_index], ratings[best_index]));
    }
    println!("{}", lines.join("\n"));
    

    Rust details worth knowing:

    • Inclusive range. 1..=k includes k, while 0..ratings.len() stops before the length. The first gives ranks, the second gives positions.
    • Inferred types. lines starts as Vec::new() with no element type. The first push of a String from format! tells Rust it is a Vec<String>. Then join("\n") glues the strings with a newline between each two and no newline after the last.
    • format! against println!. Both use the same {} placeholders, but format! returns a String instead of printing it.
    • Index types. best_index starts as 0 and is used to index vectors, so Rust makes it a usize. The loop variable i is a usize too.

    Complexity

    Time: O(k * n) for n brands, because each of the k rounds scans all of them. Space: O(n + k) for the used flags and the k output lines.

    Edge cases and common mistakes

    • Different values of k. k = 1 prints only 1. MegaCorp (5). k = 5 prints all five brands: MegaCorp, NeoByte, TechPro, Zenith and Quantum with ratings 5, 5, 4, 4 and 3. With k = 0 the loop doesn't run, lines is empty, and println! prints an empty line.
    • Ties. Brands X, Y and Z, all rated 3, with k = 3 come out as X, Y, Z. The strict > keeps the earlier brand in front. With >= a later brand would replace it.
    • A single brand. Brand Solo rated 2 with k = 1 prints 1. Solo (2).
    • k larger than the number of brands. The lesson rules it out, and the code doesn't check for it. Two brands A (1) and B (2) with k = 3 print 1. B (2), 2. A (1) and then 3. A (1): in the third round nothing is left, so best_index stays at 0 and brand 0 repeats.
    • Not marking the winner. Without used[best_index] = true, every round finds MegaCorp again.
    • Dropping the found flag. A comparison that starts from best_index = 0 would compare against a brand that may be taken already.

    Testing

    • The lesson's data with k = 3 prints 1. MegaCorp (5), 2. NeoByte (5) and 3. TechPro (4).
    • k = 1 prints 1. MegaCorp (5).
    • k = 5 prints all five brands, ending with 5. Quantum (3).
    • One brand Solo with rating 2 and k = 1 prints 1. Solo (2).
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free