Start learning free

LESSON 253 OF 289 · NESTED LOOPS

Top K Brands V4 in C#: Top K by Repeating the Search

Practice Read the full explanation

Show the top k brands by rating. This is v3's search, repeated k times: find the best brand, mark it as taken, then search again among the brands that are not taken yet, until you have k brands in rank order.

You start with:

        string[] brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
        int[] ratings = {4, 5, 3, 5, 4};
        int k = 3;

Build:

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

Rules:

  • Repeat v3's search k times. Each round looks only at brands that are not taken yet and picks the one with the highest rating, then marks it as taken (one true/false flag per brand).
  • Ties go to the brand listed first: keep the first brand you find and replace it only on a strictly higher rating.
  • k is never larger than the number of brands.
  • Each line is "rank. Brand (rating)", starting at rank 1.
  • Print the lines, one per line, with Console.WriteLine(...).

Start with the two declarations bool[] used = new bool[ratings.Length]; and List<string> lines = new List<string>();. A flag tells whether that position is already taken.

Each round is v3's search: nothing found yet, scan every position, skip taken ones, keep the first candidate and replace it only on a strictly higher rating. Then mark the winner as taken and add its line.

        string[] brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
        int[] ratings = {4, 5, 3, 5, 4};
        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 || ratings[i] > ratings[bestIndex]) {
                        bestIndex = i;
                    }
                }
            }
            used[bestIndex] = true;
            lines.Add(rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");
        }
        Console.WriteLine(string.Join("\n", lines));

STEP 1 OF 11
    Ctrl + Enter to check

    C# · NESTED LOOPS

    Top K Brands V4 in C#, explained

    Problem overview

    The previous version found the single best brand. This version prints the top k brands in rank order, without sorting anything. The data is two parallel arrays, brands and ratings, where ratings[i] belongs to brands[i], plus an int named k. Each output line has the form rank. Brand (rating), starting at rank 1. Ties go to the brand listed first, and k is never larger than the number of brands.

    The starter data has five brands: TechPro 4, MegaCorp 5, Quantum 3, NeoByte 5 and Zenith 4, with k = 3. MegaCorp and NeoByte tie at 5, and MegaCorp comes first. TechPro and Zenith tie at 4, and TechPro comes first. The output is:

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

    Approach: search, mark, search again

    Finding the best brand is a loop with a "best so far" index: start with nothing chosen, visit every position, and replace the choice only when a rating is strictly higher. Strictly higher is what gives the tie rule, because an equal rating never pushes out the brand found earlier.

    To get the second best, run the same search again, but ignore the brand that already won. A bool array named used, with one flag per brand, records who is taken. The search considers only brands whose flag is still false. After every round, the winner's flag becomes true, so the next round finds the best among the rest. Doing this k times produces the brands in rank order.

    This is a pair of nested loops. The outer loop counts the ranks, and the inner loop scans all the brands for each rank. The work is about k times n comparisons, which is fine for a few brands. Sorting is not needed, and the original arrays stay in their original order.

    Tracing the example: in round 1 the search sees TechPro (4), then MegaCorp (5) replaces it, and nothing later beats 5, so MegaCorp wins. In round 2, MegaCorp is skipped, so TechPro is the first candidate, Quantum (3) does not beat it, NeoByte (5) does, and Zenith (4) does not beat 5. NeoByte wins. In round 3 only TechPro (4), Quantum (3) and Zenith (4) are left. TechPro is found first and Zenith's 4 is not strictly higher, so TechPro takes third place.

    Step by step

    1. Create used as new bool[ratings.Length]. C# fills a new bool array with false, which means nobody is taken yet.
    2. Create lines as an empty List<string>. Each round adds one finished line, and the list grows as needed, which an array could not do.
    3. Write the outer loop with rank from 1 up to and including k. Starting at 1 means the same variable is also the number printed in front of the brand.
    4. Create bestIndex at -1 inside the loop. No brand has index -1, so it means that nothing has been found in this round. Declaring it inside the outer loop restarts the search every round.
    5. Write the inner loop over i from 0 to ratings.Length. Each round looks at every brand again.
    6. Skip taken brands. The first if is !used[i]: only brands that have not won are candidates.
    7. Test the candidate. The second if is true when nothing is chosen yet (bestIndex == -1) or the rating is strictly higher than that of bestIndex.
    8. Remember it with bestIndex = i. The position is enough, since the name and the rating are read from it later.
    9. Mark the winner after the inner loop: used[bestIndex] = true. It happens right away, because the next round reads the flag.
    10. Build the line with rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ")" and add it to lines.
    11. Print after the loop with string.Join("\n", lines) inside Console.WriteLine, which puts a newline between every two lines.

    The solution in C#

            string[] brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
            int[] ratings = {4, 5, 3, 5, 4};
            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 || ratings[i] > ratings[bestIndex]) {
                            bestIndex = i;
                        }
                    }
                }
                used[bestIndex] = true;
                lines.Add(rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");
            }
            Console.WriteLine(string.Join("\n", lines));
    

    Details worth knowing:

    • Short-circuit ||. In bestIndex == -1 || ratings[i] > ratings[bestIndex], when bestIndex is -1 the right side is never evaluated. That protects ratings[-1], which would throw an IndexOutOfRangeException.
    • int plus string. In rank + ". " + ... the first + has an int on the left and a string on the right, so C# turns the number into text and concatenates. What matters is where the string enters the expression: 1 + 2 + ". x" gives 3. x because the numbers are added first, while ". x" + 1 + 2 would give . x12.
    • List<T> and using. List<string> lives in System.Collections.Generic, so a standalone file needs using System.Collections.Generic;. Its size is Count, and Add appends at the end.
    • string.Join. It glues the elements of any sequence of strings together with a separator between them and none at the end. For an empty list the result is an empty string, so Console.WriteLine prints a single blank line.
    • Arrays start as defaults. A new bool[n] holds false in every slot, a new int[n] holds 0, and a new string[n] holds null.

    Complexity

    Let n be the number of brands.

    Time: O(k * n). The outer loop runs k times, and each round scans all n positions with constant work per position. Since k is at most n, the worst case is O(n^2), reached when k equals n and the search effectively becomes a selection sort that writes down the order. Sorting once and taking the first k would cost O(n log n).

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

    Edge cases and common mistakes

    • Ties. With the starter data, NeoByte follows MegaCorp and TechPro precedes Zenith, because every comparison is strictly greater. Writing >= would let the later brand of each tie replace the earlier one, and the output would start with 1. NeoByte (5).
    • k equal to the number of brands. With k = 5 every brand is printed once, ending with 5. Quantum (3). Zenith comes fourth, after TechPro, because they tie at 4.
    • k = 1. The program prints only 1. MegaCorp (5), which is the previous version's result.
    • k larger than the number of brands. The lesson promises this does not happen. If it did, the extra round would find nothing, bestIndex would stay -1, and used[bestIndex] would throw an IndexOutOfRangeException with the message "Index was outside the bounds of the array."
    • Forgetting to mark the winner. Every round would pick the same brand, and the output would repeat it k times with different ranks.
    • Declaring bestIndex outside the outer loop. It would start the next round on the previous winner, who is already taken. No remaining brand has a strictly higher rating, so that index never changes and the output repeats the first winner with new ranks.
    • Starting the rank at 0. The lines would read 0. MegaCorp (5). The lesson numbers from 1.

    Testing

    • The starter data with k = 3 prints the three lines shown at the top.
    • With k = 1 only 1. MegaCorp (5) prints.
    • With k = 5 the lines are MegaCorp (5), NeoByte (5), TechPro (4), Zenith (4) and Quantum (3), numbered 1 to 5.

    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