Start learning free

LESSON 259 OF 293 · NESTED LOOPS

Top K Brands V6 in Rust: Ranking with a Tie-Breaker

Practice Read the full explanation

Rank the top k brands by rating, breaking ties with the review count. This builds on v4's repeated search (not on v5: there is no filtering here); only the comparison gets a second criterion.

You start with:

    let brands = vec!["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"];
    let ratings = vec![4, 5, 5, 3, 4];
    let reviews = vec![200, 150, 500, 100, 300];
    let k = 3;

Build:

1. NeoByte (5, 500)
2. MegaCorp (5, 150)
3. Zenith (4, 300)

Rules:

  • Rating decides first: the higher rating wins.
  • If two brands have the same rating, the one with more reviews wins.
  • If rating and reviews are both equal, the one listed first wins (the test data has no such pair, but your code must follow the rule).
  • k is never larger than the number of brands.
  • Each line is "rank. Brand (rating, reviews)", starting at rank 1.
  • Print the lines, one per line, with println!(...).

Start from v4: the same let mut used = vec![false; ratings.len()]; and let mut lines = Vec::new();, the same two loops. Only the comparison inside the inner loop changes.

Use a chain (if / else if / else if): no candidate yet, take this one; else a higher rating, take this one; else the same rating and more reviews, take this one.

let brands = vec!["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"];
let ratings = vec![4, 5, 5, 3, 4];
let reviews = vec![200, 150, 500, 100, 300];
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 {
                best_index = i;
                found = true;
            } else if ratings[i] > ratings[best_index] {
                best_index = i;
            } else if ratings[i] == ratings[best_index] && reviews[i] > reviews[best_index] {
                best_index = i;
            }
        }
    }
    used[best_index] = true;
    lines.push(format!("{}. {} ({}, {})", rank, brands[best_index], ratings[best_index], reviews[best_index]));
}
println!("{}", lines.join("\n"));

STEP 1 OF 17
    Ctrl + Enter to check

    RUST · NESTED LOOPS

    Top K Brands V6 in Rust, explained

    Problem overview

    Five brands have a rating and a review count: TechPro (4, 200), MegaCorp (5, 150), NeoByte (5, 500), Quantum (3, 100) and Zenith (4, 300). The program prints the top k brands, here k = 3, as rank. Brand (rating, reviews):

    1. NeoByte (5, 500)
    2. MegaCorp (5, 150)
    3. Zenith (4, 300)
    

    The rating decides first. When two brands have the same rating, the one with more reviews wins. If both are equal, the brand listed first wins; the lesson's data has no such pair, but the code follows the rule anyway. The input guarantees that k is never larger than the number of brands.

    This version builds on the repeated search from version 4: find the best brand, mark it as taken, search again among the rest. There is no filtering here. Only the comparison changes, because it now has a second criterion.

    Approach: a comparison with two criteria

    The search keeps best_index, the position of the best brand so far in this round, and found, which says whether a round has picked a brand yet. A vector used flags the winners of earlier rounds so they are skipped.

    For each brand that is not used, one of three cases applies, tested in order:

    1. Nothing has been found yet: this brand is the best so far.
    2. Its rating is higher than the best one's: it becomes the best, whatever the review counts are.
    3. Its rating equals the best one's and it has more reviews: it becomes the best.

    Because the cases form an else if chain, the third one only runs when the ratings are not different in the brand's favor. Reviews matter only as a tie-breaker. A brand with a lower rating never wins by review count.

    When rating and reviews are both equal, none of the cases fires, so best_index keeps the earlier brand. Strict comparisons in cases 2 and 3 give the tie rule for free.

    Step by step

    1. Create brands with TechPro, MegaCorp, NeoByte, Quantum and Zenith.
    2. Create ratings as 4, 5, 5, 3 and 4.
    3. Create reviews as 200, 150, 500, 100 and 300, lined up with the brands by position.
    4. Create k as 3.
    5. Create used with vec![false; ratings.len()], using let mut.
    6. Create lines as an empty vector with Vec::new().
    7. Loop over the ranks with for rank in 1..=k.
    8. Create best_index inside the loop, starting at 0.
    9. Create found inside the loop, starting at false.
    10. Open the inner loop over every position i of ratings.
    11. Skip used brands with an if on !used[i].
    12. First case: if nothing is found yet, set best_index to i and found to true.
    13. Second case: an else if for a higher rating than the best one's, setting best_index to i.
    14. Third case: an else if for an equal rating and more reviews, setting best_index to i.
    15. After the inner loop, set used[best_index] to true.
    16. Add the line to lines with push and format!: rank, dot, space, brand, then the rating and the review count in parentheses, separated by a comma and a space.
    17. Print after the loop with lines.join("\n").

    The solution in Rust

    let brands = vec!["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"];
    let ratings = vec![4, 5, 5, 3, 4];
    let reviews = vec![200, 150, 500, 100, 300];
    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 {
                    best_index = i;
                    found = true;
                } else if ratings[i] > ratings[best_index] {
                    best_index = i;
                } else if ratings[i] == ratings[best_index] && reviews[i] > reviews[best_index] {
                    best_index = i;
                }
            }
        }
        used[best_index] = true;
        lines.push(format!("{}. {} ({}, {})", rank, brands[best_index], ratings[best_index], reviews[best_index]));
    }
    println!("{}", lines.join("\n"));
    

    Rust details worth knowing:

    • else if chains are exclusive. Rust runs the first branch whose condition is true and skips the rest. That is why the review comparison can assume the rating is not higher.
    • && needs both sides. The third case requires equal ratings and more reviews. It short-circuits: when the ratings differ, the review comparison is not evaluated.
    • Parallel vectors. Nothing in the types ties brands, ratings and reviews together. The code relies on all three having the same length and order.
    • A tuple alternative. Rust compares tuples field by field, so (ratings[i], reviews[i]) > (ratings[best_index], reviews[best_index]) expresses the same two-level rule in one test. For example, (5, 500) > (5, 150) is true. The lesson spells out the cases instead, which makes each rule visible.

    Complexity

    Time: O(k * n) for n brands, because each of the k rounds scans every brand and each comparison takes constant time. Space: O(n + k) for the used flags and the output lines.

    Edge cases and common mistakes

    • Reviews beat rating. A brand "Low" with rating 3 and 9000 reviews, and a brand "High" with rating 5 and 1 review, come out as High first, then Low. The rating is compared before the reviews.
    • Rating and reviews both equal. Brands P and Q, both rated 4 with 10 reviews, come out as P, then Q. Both comparisons are strict, so the earlier brand stays in front.
    • A tie where the last brand has the most reviews. Brands A, B and C, all rated 5, with 1, 2 and 3 reviews, come out as C, B, A.
    • A larger k. With k = 5 on the lesson's data, the lines continue with 4. TechPro (4, 200) and 5. Quantum (3, 100).
    • Comparing reviews alone. A rule that looked only at the review counts would rank Zenith (300) above MegaCorp (150), against the lesson's expected output.

    Testing

    • The lesson's data with k = 3 prints 1. NeoByte (5, 500), 2. MegaCorp (5, 150) and 3. Zenith (4, 300).
    • The same data with k = 5 adds 4. TechPro (4, 200) and 5. Quantum (3, 100).
    • Low (3, 9000) and High (5, 1) with k = 2 print 1. High (5, 1) and 2. Low (3, 9000).
    • P (4, 10) and Q (4, 10) with k = 2 print P first.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free