Start learning free

LESSON 250 OF 285 · NESTED LOOPS

Top K Brands V4 in Java: Repeated Search with Nested Loops

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 System.out.println(...).

Start with the two declarations boolean[] used = new boolean[ratings.length]; and List<String> lines = new ArrayList<>();. 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;

boolean[] used = new boolean[ratings.length];
List<String> lines = new ArrayList<>();
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] + ")");
}
System.out.println(String.join("\n", lines));

STEP 1 OF 11
    Ctrl + Enter to check

    JAVA · NESTED LOOPS

    Top K Brands V4 in Java, explained

    Problem overview

    Two parallel arrays describe a set of brands: brands holds the names and ratings holds their ratings. The program must print the top k brands by rating, best first, one per line, in the form rank. Brand (rating). Ranks start at 1, and ties go to the brand listed first.

    With k = 3 and the starting data, MegaCorp and NeoByte both have rating 5, and MegaCorp is listed first. TechPro and Zenith both have 4, and TechPro is listed first. The output is:

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

    The lesson says k is never larger than the number of brands.

    Approach: find the best, mark it, search again

    Version 3 of this project finds the single best brand: scan every position, remember the best so far and replace it only when a rating is strictly higher. Version 4 repeats that search k times, and each round excludes the brands that already won.

    A boolean array named used keeps this memory: used[i] is true once brand i has been given a rank. Each round scans the positions that are not used, picks the best, marks it as used and records its line. The round number is also the rank to print.

    The search stores a position, bestIndex, not a rating, because both the name and the rating are read from that position later. The value -1 means that nothing has been found yet in this round.

    Sorting the brands would be the other way to get a top k, but sorting two parallel arrays together is awkward, and this lesson practises nested loops.

    Step by step

    1. Create used. new boolean[ratings.length] gives one flag per brand, all false at the start.
    2. Create lines. A List<String> set to a new ArrayList collects one finished line per rank, starting empty.
    3. Write the outer loop. rank goes from 1 up to and including k, so with k = 3 it takes the values 1, 2 and 3. It counts the rounds and is also printed in front of the brand name.
    4. Reset bestIndex. Inside the round, int bestIndex = -1; starts every search from nothing found.
    5. Write the inner loop. i takes every position of ratings. For each round of the outer loop, the inner one runs through all the brands from the start. That is what makes the loops nested.
    6. Skip taken brands. An if (!used[i]) makes only the brands without a rank candidates.
    7. Compare. Inside it, a second if is true when nothing is found yet (bestIndex == -1) or when this rating is strictly higher than the best one's. The strict comparison leaves a tie with the earlier brand.
    8. Remember the brand. Set bestIndex to i.
    9. Mark the winner. After the inner loop, set used[bestIndex] to true, so the next round can't pick it again.
    10. Add the line. Build it as the rank, a dot and a space, the brand's name, then the rating in parentheses, and add it to lines. Java's + turns the int values into text when it joins them to a String.
    11. Print. After the loop, String.join("\n", lines) glues the lines together with a newline between each two, and System.out.println prints the result.

    The solution in Java

    String[] brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
    int[] ratings = {4, 5, 3, 5, 4};
    int k = 3;
    
    boolean[] used = new boolean[ratings.length];
    List<String> lines = new ArrayList<>();
    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] + ")");
    }
    System.out.println(String.join("\n", lines));
    

    The Java details worth a closer look:

    • rank + ". " + .... The expression starts with an int, but the next operand is a string, so from there on everything is joined as text. The result is 1. MegaCorp (5).
    • String.join. It takes a separator and an iterable of strings, here the list. There is no separator after the last line, so the output has no blank line at the end.
    • Short-circuit ||. When bestIndex is -1, the right side is not evaluated, so ratings[-1] is never read.
    • Default flags. A new boolean[] starts all false, which is what "nobody has a rank yet" needs.

    Complexity

    Time: O(k * n) for n brands. Each of the k rounds scans all n positions. With k as large as n this is O(n²).

    Space: O(n + k): the used flags take n slots, and lines holds k strings.

    Edge cases and common mistakes

    • Ties. The strict > keeps the first brand. With >= the starting data would print NeoByte first, then MegaCorp, then Zenith. The expected order is MegaCorp, NeoByte, TechPro.
    • k equal to the number of brands. With k = 5 the output is MegaCorp (5), NeoByte (5), TechPro (4), Zenith (4) and Quantum (3), each on its own line.
    • k = 1. The output is the single line 1. MegaCorp (5).
    • k larger than the number of brands. The lesson rules this out. If it happened, a round with no brand left would leave bestIndex at -1, and used[-1] would throw ArrayIndexOutOfBoundsException. With k = 6 on the five starting brands the message is Index -1 out of bounds for length 5.
    • Forgetting to mark the winner. Without used[bestIndex] = true, every round finds the same brand.
    • Declaring bestIndex outside the outer loop. A stale index from the last round would be compared in the next one.
    • Printing inside the loop. The lesson collects the lines and prints once with String.join. Printing inside the loop gives the same lines, but the collected form keeps the output code in one place.

    Testing

    • k = 1 gives 1. MegaCorp (5).
    • k = 3 gives the three lines above.
    • k = 5 gives five lines, ending with 5. Quantum (3).
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free