Start learning free

LESSON 252 OF 671 · NESTED LOOPS

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

Build filteredBrands and filteredRatings first: a loop over the catalog that copies the row when products[i].equals(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 ArrayList<>();
List<Integer> filteredRatings = new ArrayList<>();
for (int i = 0; i < products.length; i++) {
    if (products[i].equals(target)) {
        filteredBrands.add(brands[i]);
        filteredRatings.add(ratings[i]);
    }
}
boolean[] used = new boolean[filteredRatings.size()];
List<String> lines = new ArrayList<>();
for (int rank = 1; rank <= k; rank++) {
    int bestIndex = -1;
    for (int i = 0; i < filteredRatings.size(); i++) {
        if (!used[i]) {
            if (bestIndex == -1 || filteredRatings.get(i) > filteredRatings.get(bestIndex)) {
                bestIndex = i;
            }
        }
    }
    if (bestIndex != -1) {
        used[bestIndex] = true;
        lines.add(rank + ". " + filteredBrands.get(bestIndex) + " (" + filteredRatings.get(bestIndex) + ")");
    }
}
System.out.println(String.join("\n", lines));

STEP 1 OF 18
    Ctrl + Enter to check

    JAVA · NESTED LOOPS

    Top K Brands V5 in Java, explained

    Problem overview

    The catalog now has several products. Three parallel arrays describe it: products, brands and ratings, where row i is one product, the brand that sells it and its rating. The program gets a target product and a number k, and prints the top k brands for that product, in the form rank. Brand (rating).

    With target = "Laptop" and k = 2, three rows match: TechPro (4), NeoByte (5) and AlphaTech (4). The two best are NeoByte and TechPro. TechPro wins the tie with AlphaTech because it is listed first:

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

    If fewer than k rows match, the program lists only the ones that exist, with no error and no extra lines.

    Approach: two stages

    The work splits into two stages. First, filter: copy the brand and the rating of every row whose product equals target into two new lists, keeping the original order. Second, rank: run the repeated search from version 4, but on the filtered lists, not on the original arrays.

    Filtering first keeps the search simple. The search never has to ask whether a row belongs to the target product, because only matching rows are in the lists it scans. The two filtered lists stay in step: the brand at position 0 of one has its rating at position 0 of the other.

    The ranking stage is version 4's: each round scans the brands that aren't taken yet, keeps the first candidate, replaces it only on a strictly higher rating, marks the winner and records a line. One thing changes. With a filter, there may be fewer brands than k, so a round can find nobody, and then it must add no line.

    Step by step

    1. Create filteredBrands. A List<String> set to a new ArrayList, empty at the start. It will hold the brands that sell the target product.
    2. Create filteredRatings. A List<Integer> set to a new ArrayList, for the ratings of those brands.
    3. Visit every row. A for loop with i over each position of products. The three arrays line up, so row i is a product, its brand and its rating.
    4. Test the product. An if that is true when products[i] equals target. Rows of other products are skipped.
    5. Copy the brand. Inside the if, add brands[i] to filteredBrands.
    6. Copy the rating. Add ratings[i] to filteredRatings the same way, so the pair stays at the same position in both lists.
    7. Create used. A boolean array with one slot for each filtered rating, all false. It is as long as the filtered lists, not the original arrays.
    8. Create lines. An empty List<String> for the finished lines.
    9. Write the outer loop. rank from 1 up to and including k: one round per rank.
    10. Reset bestIndex. int bestIndex = -1; at the start of each round.
    11. Write the inner loop. i over every position of filteredRatings.
    12. Skip taken entries. if (!used[i]).
    13. Compare. Inside it, an if for "nothing found yet, or this rating is strictly higher than the best one's".
    14. Remember it. Set bestIndex to i.
    15. Check that a brand was found. After the inner loop, if (bestIndex != -1). When fewer than k brands match, the late rounds find nobody and add no line.
    16. Mark the winner by setting used[bestIndex] to true.
    17. Add the line. The rank, a dot and a space, the brand, then the rating in parentheses. A list is read with get, not with square brackets.
    18. Print. String.join("\n", lines) inside System.out.println.

    The solution in Java

    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 ArrayList<>();
    List<Integer> filteredRatings = new ArrayList<>();
    for (int i = 0; i < products.length; i++) {
        if (products[i].equals(target)) {
            filteredBrands.add(brands[i]);
            filteredRatings.add(ratings[i]);
        }
    }
    boolean[] used = new boolean[filteredRatings.size()];
    List<String> lines = new ArrayList<>();
    for (int rank = 1; rank <= k; rank++) {
        int bestIndex = -1;
        for (int i = 0; i < filteredRatings.size(); i++) {
            if (!used[i]) {
                if (bestIndex == -1 || filteredRatings.get(i) > filteredRatings.get(bestIndex)) {
                    bestIndex = i;
                }
            }
        }
        if (bestIndex != -1) {
            used[bestIndex] = true;
            lines.add(rank + ". " + filteredBrands.get(bestIndex) + " (" + filteredRatings.get(bestIndex) + ")");
        }
    }
    System.out.println(String.join("\n", lines));
    

    The Java details worth a closer look:

    • equals, not ==. On strings, == asks whether two variables point at the same object, and equals compares the characters. A String built with new String("Laptop") is not == to the literal "Laptop", although equals says they match. Use equals for text.
    • Arrays versus lists. The filtered data can't go into arrays, because the number of matches is unknown in advance. An ArrayList grows with add, and its size comes from size(), not length.
    • Comparing Integer values. filteredRatings.get(i) returns an Integer. The > operator unboxes both sides to int, so the comparison in the solution is by value. With == between two Integer objects the comparison would be by reference, so it isn't safe for values like these.
    • Null elements. products[i].equals(target) would throw NullPointerException if products[i] were null. The lesson's arrays have no nulls.

    Complexity

    Time: O(n + k * m), where n is the number of rows and m the number of matching rows. The filter is one pass over the n rows, and each of the k rounds scans the m filtered entries.

    Space: O(m + k): the two filtered lists and the used flags take m slots each, and the lines take k.

    Edge cases and common mistakes

    • Fewer matches than k. With target = "Laptop" and k = 5, only three rows match, and the output is the three lines NeoByte (5), TechPro (4) and AlphaTech (4). With target = "Tablet" and k = 2 only 1. Quantum (3) is printed.
    • No match at all. With target = "Camera", the filtered lists are empty, no line is added, and String.join of an empty list is an empty string. The program prints an empty line.
    • A different product. target = "Phone" and k = 2 give 1. MegaCorp (5) and 2. Zenith (4).
    • Sizing used from the original arrays. The flags belong to the filtered lists. A longer used array does not crash, but it is easy to confuse the two sets of positions: the indexes in the search are filtered positions, not row numbers.
    • Missing the bestIndex != -1 check. The late rounds would use -1 as a list position and throw an exception.
    • Using row numbers for the winner. The names and ratings must come from the filtered lists at bestIndex. Reading brands[bestIndex] would return a brand of a different product.
    • Ties. The strict > keeps the entry listed first, so TechPro stays ahead of AlphaTech.

    Testing

    • target = "Laptop", k = 2 gives 1. NeoByte (5) and 2. TechPro (4).
    • target = "Laptop", k = 3 adds 3. AlphaTech (4).
    • target = "Phone", k = 2 gives 1. MegaCorp (5) and 2. Zenith (4).
    • target = "Tablet", k = 2 gives only 1. Quantum (3).
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free