Start learning free

LESSON 191 OF 293 · LOOPING OVER ARRAY INDICES

Top K Brands V3 in Rust: Finding the Best in a Vector

Practice Read the full explanation

Many brands sell the same product, stored in two parallel vectors: ratings[i] is the rating of brands[i]. Find the highest-rated brand by scanning with a loop.

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];

Build:

1. MegaCorp (5)

Rules:

  • Keep the position of the best brand so far in best_index, starting at 0, and scan the positions from 1 to the end with a loop.
  • Update best_index only on a strictly higher rating. If two brands share the top rating, the one listed first wins (MegaCorp at position 1, not NeoByte at position 3).
  • Format the winner as "1. Brand (rating)" and print it with println!(...).

Walk the positions with for i in 1..ratings.len() { and compare each rating with the best one so far.

format!("1. {} ({})", brand, rating) builds text from several values, numbers included.

        let brands = vec!["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
        let ratings = vec![4, 5, 3, 5, 4];
        let mut best_index = 0;
        for i in 1..ratings.len() {
            if ratings[i] > ratings[best_index] {
                best_index = i;
            }
        }
        println!("1. {} ({})", brands[best_index], ratings[best_index]);

STEP 1 OF 7
    Ctrl + Enter to check

    RUST · LOOPING OVER ARRAY INDICES

    Top K Brands V3 in Rust, explained

    Problem overview

    Many brands sell the same product. Their names are in a vector brands and their ratings in a vector ratings, with ratings[i] belonging to brands[i]. The program scans the lists to find the highest-rated brand and prints it as 1. Brand (rating). If two brands share the top rating, the one listed first wins.

    The lesson starts with an empty editor, so you declare the data: five brands, TechPro, MegaCorp, Quantum, NeoByte and Zenith, with ratings 4, 5, 3, 5 and 4. The top rating, 5, appears twice, at positions 1 and 3. MegaCorp is listed first, so the output is:

    1. MegaCorp (5)
    

    The previous version compared two brands with an if/else. A list can hold any number of brands, so this version uses a loop.

    Approach: a running champion

    Keep the position of the best brand seen so far, best_index, and start it at 0: until something better turns up, the first brand is the best. A loop then visits the positions from 1 to the end. For each one, it compares that brand's rating with the rating at best_index, and if it is strictly higher, best_index moves there.

    The program stores a position and not the best rating, because one position gives both the brand and its rating: brands[best_index] and ratings[best_index].

    The strictness of the comparison implements the tie rule. When a later brand merely equals the current best, the condition is false, so the earlier brand stays in front. That is how MegaCorp keeps its lead over NeoByte.

    Step by step

    1. Declare brands with vec! in the given order, since the ratings line up with it by position.
    2. Declare ratings as 4, 5, 3, 5, 4, in the same order.
    3. Create best_index with let mut and the value 0. It needs mut because it changes.
    4. Start the loop with for i in 1..ratings.len(). It begins at 1 because position 0 is already the best so far, and it stops before the length.
    5. Compare in the loop. An if checks whether ratings[i] is strictly greater than ratings[best_index].
    6. Move the champion. Inside the if, set best_index to i.
    7. Print after the loop using the brand and the rating at best_index in the 1. Brand (rating) template.

    The solution in Rust

            let brands = vec!["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
            let ratings = vec![4, 5, 3, 5, 4];
            let mut best_index = 0;
            for i in 1..ratings.len() {
                if ratings[i] > ratings[best_index] {
                    best_index = i;
                }
            }
            println!("1. {} ({})", brands[best_index], ratings[best_index]);
    

    Rust details to keep in mind:

    • The range is half-open. 1..ratings.len() includes 1 and leaves out the length. For five ratings, i takes the values 1, 2, 3 and 4.
    • Index type. best_index starts as 0, but because it is used to index vectors, Rust makes it a usize. The loop variable is a usize too, so best_index = i compiles without a cast.
    • Out-of-range indexing panics. A vector never silently gives a default value. Reading an index past the end stops the program with an index out of bounds message.
    • Parallel vectors. Nothing in the types ties brands to ratings. The program relies on both being the same length and the same order.

    Complexity

    Time: O(n) for n brands, because the loop visits each position once. Space: O(1) extra, because the program keeps one index.

    Edge cases and common mistakes

    • Ties. With >= instead of >, the lesson's data prints 1. NeoByte (5) instead of MegaCorp, because the later 5 takes over. Two brands that both have rating 3 give the first one, with >.
    • The best brand is first. With ratings 3, 2 and 1 the condition never holds and best_index stays 0.
    • The best brand is last. With ratings 1, 2 and 3 the loop reaches the last position and prints the third brand, with rating 3.
    • One brand. The range 1..1 is empty, so the loop doesn't run and the only brand is printed with its rating.
    • No brands. The loop is skipped, but brands[best_index] then reads position 0 of an empty vector and the program panics with index out of bounds: the len is 0 but the index is 0.
    • Tracking the rating instead of the position. You would then have the best rating but no way to get its brand without searching again.

    Testing

    • The lesson's data prints 1. MegaCorp (5).
    • Brands A, B, C with ratings 1, 2, 3 print 1. C (3).
    • Brands A, B, C with ratings 3, 2, 1 print 1. A (3).
    • Brands A and B with ratings 3 and 3 print 1. A (3).
    • A single brand Solo with rating 2 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