Start learning free

LESSON 255 OF 289 · NESTED LOOPS

Top K Brands V6 in C#: 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:

        string[] brands = {"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"};
        int[] ratings = {4, 5, 5, 3, 4};
        int[] reviews = {200, 150, 500, 100, 300};
        int 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 Console.WriteLine(...).

Start from v4: the same bool[] used = new bool[ratings.Length]; and List<string> lines = new List<string>();, 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.

        string[] brands = {"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"};
        int[] ratings = {4, 5, 5, 3, 4};
        int[] reviews = {200, 150, 500, 100, 300};
        int k = 3;

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

STEP 1 OF 12
    Ctrl + Enter to check

    C# · NESTED LOOPS

    Top K Brands V6 in C#, explained

    Problem overview

    This version ranks the top k brands by rating, and when two ratings are equal, the brand with more reviews comes first. The data is three parallel arrays: brands, ratings and reviews, plus k. It builds on the repeated search of the fourth version, and only the comparison changes: there is no filtering here. Each line is rank. Brand (rating, reviews). If both the rating and the review count are equal, the brand listed first wins. The value of k is never larger than the number of brands.

    The starter data has five brands: TechPro (4, 200), MegaCorp (5, 150), NeoByte (5, 500), Quantum (3, 100) and Zenith (4, 300). With k = 3 the output is:

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

    MegaCorp and NeoByte tie on rating 5, and NeoByte has more reviews, so it comes first. Zenith and TechPro tie on rating 4, and Zenith's 300 reviews beat TechPro's 200.

    Approach: a two-level comparison inside the same search

    The structure is the one from the fourth version. The outer loop runs once per rank. In each round, the inner loop scans the brands that are not taken yet, keeps the best one found so far in bestIndex, then marks the winner in the used array and writes its line.

    The only new idea is what "better" means. A brand i beats the current best in exactly two situations:

    • its rating is higher, no matter how many reviews either brand has, or
    • its rating is equal and it has more reviews.

    Reviews are looked at only when the ratings are equal. If both the rating and the reviews are equal, neither case applies, so the earlier brand stays, which is the rule for full ties. Both comparisons are strict, and strictness is what gives that rule.

    The lesson writes this as a chain: the first case handles an empty choice (bestIndex == -1), the second compares ratings, and the third compares reviews when ratings are equal. Because each case of an else if chain runs only when the earlier ones were false, the third case is reached only for brands whose rating is not higher than the best one's, and its extra test ratings[i] == ratings[bestIndex] then keeps out lower ratings.

    Tracing round 1 on the starter data: TechPro (4) is first, so it is chosen. MegaCorp (5) has a higher rating and replaces it. NeoByte (5) has the same rating and 500 reviews against 150, so it replaces MegaCorp. Quantum (3) and Zenith (4) are lower. NeoByte wins. In round 2, NeoByte is skipped, and the best is again MegaCorp, whose rating of 5 nobody else can match. In round 3, only TechPro (4, 200), Quantum and Zenith (4, 300) remain, and Zenith wins on reviews.

    Step by step

    1. Create used as new bool[ratings.Length], which starts with every flag false.
    2. Create lines as an empty List<string>.
    3. Write the outer loop with rank from 1 up to and including k.
    4. Create bestIndex at -1 inside the loop. It means that nothing is chosen yet, so every round starts again.
    5. Write the inner loop over every position of ratings.
    6. Skip taken brands with if (!used[i]).
    7. First case: if (bestIndex == -1) sets bestIndex = i. The first brand that is not taken has nobody to beat.
    8. Second case: else if (ratings[i] > ratings[bestIndex]) sets bestIndex = i. A higher rating wins before reviews count.
    9. Third case: else if (ratings[i] == ratings[bestIndex] && reviews[i] > reviews[bestIndex]) sets bestIndex = i. Both parts must hold: the same rating and more reviews.
    10. Mark the winner after the inner loop with used[bestIndex] = true.
    11. Build the line from rank, the brand's name, and the rating and review count in parentheses, separated by a comma and a space, and add it to lines.
    12. Print with string.Join("\n", lines) inside Console.WriteLine.

    The solution in C#

            string[] brands = {"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"};
            int[] ratings = {4, 5, 5, 3, 4};
            int[] reviews = {200, 150, 500, 100, 300};
            int k = 3;
    
            bool[] used = new bool[ratings.Length];
            List<string> lines = new List<string>();
            for (int rank = 1; rank <= k; rank++) {
                int bestIndex = -1;
                for (int i = 0; i < ratings.Length; i++) {
                    if (!used[i]) {
                        if (bestIndex == -1) {
                            bestIndex = i;
                        }
                        else if (ratings[i] > ratings[bestIndex]) {
                            bestIndex = i;
                        }
                        else if (ratings[i] == ratings[bestIndex] && reviews[i] > reviews[bestIndex]) {
                            bestIndex = i;
                        }
                    }
                }
                used[bestIndex] = true;
                lines.Add(rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ", " + reviews[bestIndex] + ")");
            }
            Console.WriteLine(string.Join("\n", lines));
    

    Details worth knowing:

    • Why the order of the cases matters. The bestIndex == -1 case comes first because the other two read ratings[bestIndex], and ratings[-1] would throw an IndexOutOfRangeException. With the chain, a later case never runs when bestIndex is -1.
    • Two forms of the same test. The chain is equivalent to one condition: bestIndex == -1 || ratings[i] > ratings[bestIndex] || (ratings[i] == ratings[bestIndex] && reviews[i] > reviews[bestIndex]). The || operator also stops at the first true part. The chain just gives each case its own body and a place for a comment.
    • && needs both sides. The third case with && requires equal ratings and more reviews together. Writing only reviews[i] > reviews[bestIndex] would let a lower-rated brand with many reviews win.
    • Extra data in a parallel array. reviews is read with the same index as ratings and brands. Nothing in C# links the three arrays, so they must have the same length and order.
    • Printing numbers. The + between a string and an int turns the number into text, so ", " and the parentheses end up in the right places.

    Complexity

    Let n be the number of brands.

    Time: O(k * n). There are k rounds, and each scans n positions with a constant number of comparisons. With k as large as n, that is O(n^2).

    Space: O(n + k). The used array has n flags, and lines holds k strings.

    Edge cases and common mistakes

    • Looking at reviews first. A brand with a rating of 3 and 900 reviews must still rank below a brand with a rating of 4 and 10 reviews. With the lists {3, 4} and {900, 10}, the output is 1. B (4, 10) and then 2. A (3, 900).
    • Full ties. For brands A, B and C with ratings 5, 5 and 4 and reviews 10, 10 and 99, the order is A, B, C. A and B are equal in both values, so the one listed first, A, wins. Using >= for the review test would make B win.
    • Dropping the equality test. Without ratings[i] == ratings[bestIndex] in the third case, a brand with a lower rating and more reviews than the current best would replace it.
    • k equal to the number of brands. With k = 5 on the starter data the order is NeoByte (5, 500), MegaCorp (5, 150), Zenith (4, 300), TechPro (4, 200), Quantum (3, 100).
    • Too large a k. The lesson guarantees it does not happen. If it did, used[bestIndex] would throw with bestIndex still at -1.
    • Forgetting to mark the winner. The same brand would win every round.

    Testing

    • The starter data with k = 3 prints the three lines at the top.
    • With k = 5 the five lines are those listed above, numbered 1 to 5.
    • Ratings 5, 5 and 4 with reviews 10, 10 and 99 for A, B and C, and k = 3, print 1. A (5, 10), 2. B (5, 10) and 3. C (4, 99).
    • The ratings 3 and 4 with reviews 900 and 10 for A and B, and k = 2, print 1. B (4, 10) and 2. A (3, 900).
    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