Start learning free

LESSON 254 OF 289 · NESTED LOOPS

Top K Brands V5 in C#: Filter with Lists, 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:

        string[] products = {"Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"};
        string[] brands = {"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"};
        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 Console.WriteLine(...).

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.

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

        List<string> filteredBrands = new List<string>();
        List<int> filteredRatings = new List<int>();
        for (int i = 0; i < products.Length; i++) {
            if (products[i] == target) {
                filteredBrands.Add(brands[i]);
                filteredRatings.Add(ratings[i]);
            }
        }
        bool[] used = new bool[filteredRatings.Count];
        List<string> lines = new List<string>();
        for (int rank = 1; rank <= k; rank++) {
            int bestIndex = -1;
            for (int i = 0; i < filteredRatings.Count; i++) {
                if (!used[i]) {
                    if (bestIndex == -1 || filteredRatings[i] > filteredRatings[bestIndex]) {
                        bestIndex = i;
                    }
                }
            }
            if (bestIndex != -1) {
                used[bestIndex] = true;
                lines.Add(rank + ". " + filteredBrands[bestIndex] + " (" + filteredRatings[bestIndex] + ")");
            }
        }
        Console.WriteLine(string.Join("\n", lines));

STEP 1 OF 18
    Ctrl + Enter to check

    C# · NESTED LOOPS

    Top K Brands V5 in C#, explained

    Problem overview

    The catalog now covers several products. Three parallel arrays describe it: products, brands and ratings, where row i says that brand brands[i] sells product products[i] and has rating ratings[i]. A string named target says which product to rank, and k says how many brands to show. The program keeps only the rows of the target product, then ranks them with the repeated search from the previous version. Each line is rank. Brand (rating), ties go to the entry listed first, and if fewer than k brands match, only those that exist are printed.

    With the starter data, target = "Laptop" and k = 2, three rows match: TechPro 4, NeoByte 5 and AlphaTech 4. The output is:

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

    TechPro and AlphaTech tie at 4, and TechPro is listed first, so it takes second place.

    Approach: filter into lists, then repeat the search

    The work has two phases. The first phase is a filter. It scans every row, and when products[i] equals target, it copies that row's brand and rating into two new collections, keeping the original order. Nobody knows in advance how many rows will match, and an array's length is fixed when it is created, so the filtered data goes into List<string> and List<int>, which grow with Add. The two lists are filled at the same moments, so position j in one still pairs with position j in the other.

    The second phase is the previous version's search, run on the filtered lists instead of the original arrays. For each rank, scan the filtered entries that are not taken yet, keep the first one found, and replace it only on a strictly higher rating. Mark the winner as taken and write its line.

    One new situation appears: a product can have fewer than k brands, or none. Then some rounds find nobody, and bestIndex stays at -1 after the scan. Such a round must add no line, so the marking and the line building sit inside an if (bestIndex != -1) check.

    Step by step

    1. Create filteredBrands as an empty List<string> and filteredRatings as an empty List<int>. They will hold the rows that sell the target product.
    2. Loop over every row with i from 0 to products.Length. The same i is valid in all three arrays.
    3. Test the row with if (products[i] == target). For strings, == compares the characters, so no Equals call is needed.
    4. Copy the row. Inside the if, add brands[i] to filteredBrands and ratings[i] to filteredRatings, in the same order, so a brand and its rating stay at the same position.
    5. Create used as new bool[filteredRatings.Count]: one flag per filtered entry, all false. Its length comes from the filtered list, not from the original arrays.
    6. Create lines as an empty List<string> for the finished lines.
    7. Write the rank loop with rank from 1 up to and including k, and create bestIndex at -1 inside it so each round starts with nobody chosen.
    8. Write the inner loop over every position of filteredRatings. A position is a candidate when !used[i]. Inside that if, a second one tests bestIndex == -1 || filteredRatings[i] > filteredRatings[bestIndex], and when true it sets bestIndex = i.
    9. Check that someone was found with if (bestIndex != -1) after the inner loop. Inside it, set used[bestIndex] = true, then add the line built from rank, filteredBrands[bestIndex] and filteredRatings[bestIndex].
    10. Print after the loops with string.Join("\n", lines) inside Console.WriteLine.

    The solution in C#

            string[] products = {"Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"};
            string[] brands = {"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"};
            int[] ratings = {4, 5, 5, 3, 4, 4};
            string target = "Laptop";
            int k = 2;
    
            List<string> filteredBrands = new List<string>();
            List<int> filteredRatings = new List<int>();
            for (int i = 0; i < products.Length; i++) {
                if (products[i] == target) {
                    filteredBrands.Add(brands[i]);
                    filteredRatings.Add(ratings[i]);
                }
            }
            bool[] used = new bool[filteredRatings.Count];
            List<string> lines = new List<string>();
            for (int rank = 1; rank <= k; rank++) {
                int bestIndex = -1;
                for (int i = 0; i < filteredRatings.Count; i++) {
                    if (!used[i]) {
                        if (bestIndex == -1 || filteredRatings[i] > filteredRatings[bestIndex]) {
                            bestIndex = i;
                        }
                    }
                }
                if (bestIndex != -1) {
                    used[bestIndex] = true;
                    lines.Add(rank + ". " + filteredBrands[bestIndex] + " (" + filteredRatings[bestIndex] + ")");
                }
            }
            Console.WriteLine(string.Join("\n", lines));
    

    Details worth knowing:

    • Arrays have Length, lists have Count. The loop over the catalog uses products.Length, and the loop over the filtered data uses filteredRatings.Count. Swapping them is a compile error.
    • List indexing. filteredRatings[i] reads a list just like an array, and an invalid index throws an ArgumentOutOfRangeException, where an array throws an IndexOutOfRangeException.
    • String equality. == on two string values compares contents, so products[i] == target is true for any text spelled the same. It is case-sensitive: "Laptop" == "laptop" is false.
    • The index shift. Position i in the filtered lists is not position i in the catalog. NeoByte sits at position 2 of brands but at position 1 of filteredBrands. The search must use only filtered positions.
    • The variable i is reused. The filter loop and the inner search loop both declare int i. That is legal because each i lives only inside its own loop, and the two loops are not nested. Two loops nested inside one another cannot reuse the name, though, which is why the outer loop is called rank.
    • string.Join with no lines returns an empty string, so Console.WriteLine prints a blank line.

    Complexity

    Let n be the number of rows and m the number of rows that match the target, so m is at most n.

    Time: O(n + k * m). The filter looks at every row once. Each of the k rounds then scans m filtered entries. In the worst case all rows match and k is as large as n, which makes O(n^2).

    Space: O(n). The filtered lists and the used array together hold up to m entries each, and lines holds at most min(k, m) strings.

    Edge cases and common mistakes

    • Fewer matches than k. For "Tablet" with k = 3 only one row matches, and the output is the single line 1. Quantum (3). The two extra rounds find nobody and add nothing.
    • No match at all. For "Camera", filteredRatings is empty, every round finds nobody, and the program prints one blank line without throwing. A spelling difference such as "laptop" gives the same result.
    • Ties. For "Laptop" with k = 3, the third line is 3. AlphaTech (4), after TechPro. For "Phone" with k = 2 the output is 1. MegaCorp (5) and 2. Zenith (4).
    • Dropping the bestIndex != -1 check. used[-1] would throw an IndexOutOfRangeException as soon as a round finds nobody.
    • Sizing used from ratings. The flags are indexed by filtered position, so make the array as long as the filtered data, filteredRatings.Count. Mixing up the catalog's positions and the filtered positions is how wrong brands get printed.
    • Printing the ranks from the original positions. The rank is the loop counter, not an array index.

    Testing

    • "Laptop" with k = 2 prints 1. NeoByte (5) and 2. TechPro (4).
    • "Laptop" with k = 5 prints three lines: NeoByte (5), TechPro (4) and AlphaTech (4).
    • "Phone" with k = 2 prints 1. MegaCorp (5) and 2. Zenith (4).
    • "Tablet" with k = 3 prints 1. Quantum (3).
    • "Camera" with k = 2 prints a blank line.

    The next version builds on this one.

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