Start learning free

LESSON 251 OF 667 · NESTED LOOPS

Top K Brands V5 in C++: 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:

vector<string> products = {"Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"};
vector<string> brands = {"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"};
vector<int> ratings = {4, 5, 5, 3, 4, 4};
string target = "Laptop";
int 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 cout << ... << endl.

Build filteredBrands and filteredRatings 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 (bestIndex stays -1): add a line only when a brand was found.

vector<string> products = {"Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"};
vector<string> brands = {"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"};
vector<int> ratings = {4, 5, 5, 3, 4, 4};
string target = "Laptop";
int k = 2;

vector<string> filteredBrands;
vector<int> filteredRatings;
for (int i = 0; i < (int)products.size(); i++) {
    if (products[i] == target) {
        filteredBrands.push_back(brands[i]);
        filteredRatings.push_back(ratings[i]);
    }
}
vector<bool> used(filteredRatings.size(), false);
vector<string> lines;
for (int rank = 1; rank <= k; rank++) {
    int bestIndex = -1;
    for (int i = 0; i < (int)filteredRatings.size(); i++) {
        if (!used[i]) {
            if (bestIndex == -1 || filteredRatings[i] > filteredRatings[bestIndex]) {
                bestIndex = i;
            }
        }
    }
    if (bestIndex != -1) {
        used[bestIndex] = true;
        lines.push_back(to_string(rank) + ". " + filteredBrands[bestIndex] + " (" + to_string(filteredRatings[bestIndex]) + ")");
    }
}
for (int i = 0; i < (int)lines.size(); i++) cout << lines[i] << endl;

STEP 1 OF 18
    Ctrl + Enter to check

    C++ · NESTED LOOPS

    Top K Brands V5 in C++, explained

    Problem overview

    Version 5 works with a catalog that covers several products. Three parallel vectors describe each row: products, brands and ratings. The variable target names the product of interest, here "Laptop", and k is 2. The program keeps only the rows for that product, then prints the top k brands by rating, highest first, as rank. Brand (rating). Ties go to the entry listed first.

    Three of the six rows are laptops: TechPro (4), NeoByte (5) and AlphaTech (4). The top two are:

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

    If fewer than k products match, the program lists only the ones that exist, with no extra lines and no error. The previous version ranked every brand with a repeated search, and this one runs the same search on a filtered copy of the data.

    Approach: filter into new lists, then reuse the search

    Filtering is the first phase. Walk through every row, and whenever products[i] equals target, copy that row's brand and rating into two new vectors, filteredBrands and filteredRatings. Adding to both vectors in the same order keeps them parallel: a brand and its rating end up at the same position in the new lists.

    Ranking is the second phase, and it is the repeated search from the previous version, with two changes: it reads the filtered vectors, and it must cope with fewer than k candidates. In each round it finds the best brand that isn't marked as used, using a strict comparison so that ties stay with the earlier entry. Then it marks that brand, adds a line, and starts the next round.

    For the starter data, the first phase leaves these lists, in the original order:

    filteredBrands:  TechPro, NeoByte, AlphaTech
    filteredRatings: 4, 5, 4
    

    The second phase sees only these three entries, so a round can never pick a phone or a tablet.

    Step by step

    1. Create filteredBrands as an empty vector<string> and filteredRatings as an empty vector<int>.
    2. Loop over the rows with i through every position of products, since all three vectors line up.
    3. Test the product: an if checks products[i] == target. For string values, == compares the contents, so this is the correct test.
    4. Copy the row with push_back on both new vectors, in the same order.
    5. Create used with one false for each filtered rating, and an empty vector<string> lines.
    6. Write the outer loop with rank from 1 to k inclusive, and start each round with bestIndex = -1.
    7. Write the inner loop over the positions of filteredRatings. Skip entries with used[i] true, and pick an entry when bestIndex is -1 or its rating is strictly higher than that of bestIndex.
    8. Guard the result with if (bestIndex != -1). When fewer than k brands exist, the late rounds find nobody and add nothing.
    9. Inside the guard, mark used[bestIndex] and add the line, using to_string for the rank and the rating.
    10. Print all lines in a final loop.

    The solution in C++

    vector<string> products = {"Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"};
    vector<string> brands = {"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"};
    vector<int> ratings = {4, 5, 5, 3, 4, 4};
    string target = "Laptop";
    int k = 2;
    
    vector<string> filteredBrands;
    vector<int> filteredRatings;
    for (int i = 0; i < (int)products.size(); i++) {
        if (products[i] == target) {
            filteredBrands.push_back(brands[i]);
            filteredRatings.push_back(ratings[i]);
        }
    }
    vector<bool> used(filteredRatings.size(), false);
    vector<string> lines;
    for (int rank = 1; rank <= k; rank++) {
        int bestIndex = -1;
        for (int i = 0; i < (int)filteredRatings.size(); i++) {
            if (!used[i]) {
                if (bestIndex == -1 || filteredRatings[i] > filteredRatings[bestIndex]) {
                    bestIndex = i;
                }
            }
        }
        if (bestIndex != -1) {
            used[bestIndex] = true;
            lines.push_back(to_string(rank) + ". " + filteredBrands[bestIndex] + " (" + to_string(filteredRatings[bestIndex]) + ")");
        }
    }
    for (int i = 0; i < (int)lines.size(); i++) cout << lines[i] << endl;
    

    The search loops run over filteredRatings, and used has one flag per filtered entry. A position in the filtered lists is not a position in the full catalog. NeoByte is at position 2 in the catalog and at position 1 in the filtered lists, so mixing the two would pick the wrong brand. As written, the second phase never touches products, brands or ratings.

    The casts such as (int)products.size() in the loop headers make both sides of each comparison signed, because size() returns an unsigned value. They are harmless here and avoid surprises if an expression ever subtracts from a size.

    Complexity

    Filtering is one pass over n rows. If m rows match, the ranking takes O(k × m). The total is O(n + k × m), and the extra space is O(m) for the filtered lists and flags, plus O(k) for the lines.

    Edge cases and common mistakes

    • Fewer matches than k. For "Tablet" and k = 2, only one row matches, so the output is the single line 1. Quantum (3). Without the bestIndex != -1 check, the second round would write used[-1].
    • No match at all. For a product that isn't in the catalog, such as "Watch", the filtered vectors stay empty and the program prints nothing.
    • A larger k on laptops. With k = 5 the output is the three laptops: NeoByte (5), TechPro (4) and AlphaTech (4).
    • Ties. TechPro and AlphaTech both have 4. TechPro is listed first, so it ranks higher.
    • Another product. With "Phone" and k = 2 you get 1. MegaCorp (5) and 2. Zenith (4).
    • Copying only one vector. If you push the brand but forget the rating, the vectors drift apart and the results are wrong or out of range.

    Testing

    The starter data prints the two lines above. Change target to "Phone" or "Tablet", or set k to 5, and compare the output with the cases above.

    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free