Start learning free

LESSON 253 OF 671 · NESTED LOOPS

Top K Brands V6 in Java: 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 System.out.println(...).

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

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) {
                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] + ")");
}
System.out.println(String.join("\n", lines));

STEP 1 OF 12
    Ctrl + Enter to check

    JAVA · NESTED LOOPS

    Top K Brands V6 in Java, explained

    Problem overview

    The brands now have a second number. Three parallel arrays describe them: brands, ratings and reviews, the number of reviews behind each rating. The program prints the top k brands, best first, one per line, in the form rank. Brand (rating, reviews).

    The rating decides first. If two brands have the same rating, the one with more reviews wins. If the rating and the review count are both equal, the brand listed first wins. For the starting data and k = 3, NeoByte and MegaCorp both have rating 5, and NeoByte has 500 reviews against 150. Zenith (4, 300) comes next, ahead of TechPro (4, 200):

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

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

    Approach: version 4's search with a second criterion

    This version builds on the repeated search from version 4, and no filtering is involved. Each round scans the brands that aren't taken yet, keeps the best one found so far, marks the round's winner as taken and records a line. Only the question "is this brand better than the best so far?" changes.

    That question now has three cases, checked in order:

    1. Nothing has been found yet in this round, so this brand is the best so far.
    2. This brand's rating is higher than the best one's, so it becomes the best, whatever the reviews are.
    3. The ratings are equal and this brand has more reviews, so it becomes the best.

    Because the comparisons are strict, a brand that matches the best one on both numbers never replaces it, so the brand listed first stays ahead.

    Step by step

    1. Create used. A boolean array with a slot per brand, all false: nobody has a rank yet.
    2. Create lines. An empty ArrayList of strings, for one finished line per rank.
    3. Write the outer loop. rank from 1 up to and including k. It counts the rounds and is printed in front of each brand.
    4. Reset bestIndex. int bestIndex = -1; means nothing found yet, and each round starts the search over.
    5. Write the inner loop. i takes every position of ratings, so each round looks at all the brands from the start.
    6. Skip taken brands. if (!used[i]) keeps the brands that already have a rank out of the search.
    7. First case. If bestIndex is -1, set it to i: the first brand not taken has nobody to beat.
    8. Second case. With else if, a higher rating makes this brand the best. A case in the chain runs only when the ones above it were false.
    9. Third case. With another else if, the ratings are equal and the review count is higher. Both parts must hold, because reviews only break a tie.
    10. Mark the winner. After the inner loop, set used[bestIndex] to true.
    11. Add the line. The rank, a dot and a space, the brand, then the rating and the review count in parentheses, separated by a comma and a space.
    12. Print. String.join("\n", lines) inside System.out.println puts each rank on its own line.

    The solution in Java

    String[] brands = {"TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"};
    int[] ratings = {4, 5, 5, 3, 4};
    int[] reviews = {200, 150, 500, 100, 300};
    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) {
                    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] + ")");
    }
    System.out.println(String.join("\n", lines));
    

    The Java details worth a closer look:

    • Chain order is part of the logic. The bestIndex == -1 case comes first because the two cases below it read ratings[bestIndex]. With -1 they would throw an exception. The chain never reaches them while that first case is true.
    • == on int is a value comparison. Here ratings[i] == ratings[bestIndex] compares numbers, which is correct for primitives. (Objects like String need equals.)
    • && for "both". The third case needs the ratings to be equal and the reviews to be higher. Writing it with || would let a lower-rated brand with many reviews win.
    • Parallel arrays share an index. One bestIndex reads the name, the rating and the review count, which is why all three arrays must keep the same order.

    Complexity

    Time: O(k * n) for n brands. Each of the k rounds scans all n positions, and every comparison takes constant time. When k equals n, this is O(n²).

    Space: O(n + k): the used flags and the lines list.

    Edge cases and common mistakes

    • Dropping the "equal rating" test. If the third case only checks reviews[i] > reviews[bestIndex], a brand with a lower rating but more reviews can take the place of a better one. With two brands rated 5 with 10 reviews and 3 with 99 reviews, the loose chain picks the second brand, and the correct chain picks the first.
    • Reviews first. Ranking by reviews alone puts NeoByte (5, 500) first for the starting data, which happens to be right, but it breaks for any pair like the one above. The rating is the main criterion.
    • Full ties. With the same rating and the same reviews, the brand listed first stays first. For brands A (5, 10), B (5, 10) and C (3, 99) and k = 2, the output is A, then B.
    • k equal to the number of brands. With k = 5 the starting data prints NeoByte (5, 500), MegaCorp (5, 150), Zenith (4, 300), TechPro (4, 200) and Quantum (3, 100).
    • k larger than the number of brands. The lesson rules this out. Without a check, a round with no brand left would leave bestIndex at -1, and used[-1] would throw an exception.
    • Forgetting to mark the winner or to reset bestIndex. Either one makes later rounds repeat or compare against stale data.

    Testing

    • The starting data with k = 3 prints the three lines above.
    • The starting data with k = 5 prints five lines, ending with 5. Quantum (3, 100).
    • Brands A (5, 10), B (5, 10) and C (3, 99) with k = 2 print 1. A (5, 10) and 2. B (5, 10).
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free