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
- Create
filteredBrands. AList<String>set to a newArrayList, empty at the start. It will hold the brands that sell the target product. - Create
filteredRatings. AList<Integer>set to a newArrayList, for the ratings of those brands. - Visit every row. A
forloop withiover each position ofproducts. The three arrays line up, so rowiis a product, its brand and its rating. - Test the product. An
ifthat is true whenproducts[i]equalstarget. Rows of other products are skipped. - Copy the brand. Inside the
if, addbrands[i]tofilteredBrands. - Copy the rating. Add
ratings[i]tofilteredRatingsthe same way, so the pair stays at the same position in both lists. - Create
used. Abooleanarray with one slot for each filtered rating, allfalse. It is as long as the filtered lists, not the original arrays. - Create
lines. An emptyList<String>for the finished lines. - Write the outer loop.
rankfrom 1 up to and includingk: one round per rank. - Reset
bestIndex.int bestIndex = -1;at the start of each round. - Write the inner loop.
iover every position offilteredRatings. - Skip taken entries.
if (!used[i]). - Compare. Inside it, an
iffor "nothing found yet, or this rating is strictly higher than the best one's". - Remember it. Set
bestIndextoi. - Check that a brand was found. After the inner loop,
if (bestIndex != -1). When fewer thankbrands match, the late rounds find nobody and add no line. - Mark the winner by setting
used[bestIndex]totrue. - 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. - Print.
String.join("\n", lines)insideSystem.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, andequalscompares the characters. AStringbuilt withnew String("Laptop")is not==to the literal"Laptop", althoughequalssays they match. Useequalsfor text.- Arrays versus lists. The filtered data can't go into arrays, because the number of matches is unknown in advance. An
ArrayListgrows withadd, and its size comes fromsize(), notlength. - Comparing
Integervalues.filteredRatings.get(i)returns anInteger. The>operator unboxes both sides toint, so the comparison in the solution is by value. With==between twoIntegerobjects the comparison would be by reference, so it isn't safe for values like these. - Null elements.
products[i].equals(target)would throwNullPointerExceptionifproducts[i]werenull. 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. Withtarget = "Laptop"andk = 5, only three rows match, and the output is the three lines NeoByte (5), TechPro (4) and AlphaTech (4). Withtarget = "Tablet"andk = 2only1. Quantum (3)is printed. - No match at all. With
target = "Camera", the filtered lists are empty, no line is added, andString.joinof an empty list is an empty string. The program prints an empty line. - A different product.
target = "Phone"andk = 2give1. MegaCorp (5)and2. Zenith (4). - Sizing
usedfrom the original arrays. The flags belong to the filtered lists. A longerusedarray 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 != -1check. 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. Readingbrands[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 = 2gives1. NeoByte (5)and2. TechPro (4).target = "Laptop",k = 3adds3. AlphaTech (4).target = "Phone",k = 2gives1. MegaCorp (5)and2. Zenith (4).target = "Tablet",k = 2gives only1. Quantum (3).
