Problem overview
The catalog now covers several products. Three parallel arrays describe it: products, brands and ratings, where row i says that brand brands[i] sells product products[i] and has rating ratings[i]. A string named target says which product to rank, and k says how many brands to show. The program keeps only the rows of the target product, then ranks them with the repeated search from the previous version. Each line is rank. Brand (rating), ties go to the entry listed first, and if fewer than k brands match, only those that exist are printed.
With the starter data, target = "Laptop" and k = 2, three rows match: TechPro 4, NeoByte 5 and AlphaTech 4. The output is:
1. NeoByte (5)
2. TechPro (4)
TechPro and AlphaTech tie at 4, and TechPro is listed first, so it takes second place.
Approach: filter into lists, then repeat the search
The work has two phases. The first phase is a filter. It scans every row, and when products[i] equals target, it copies that row's brand and rating into two new collections, keeping the original order. Nobody knows in advance how many rows will match, and an array's length is fixed when it is created, so the filtered data goes into List<string> and List<int>, which grow with Add. The two lists are filled at the same moments, so position j in one still pairs with position j in the other.
The second phase is the previous version's search, run on the filtered lists instead of the original arrays. For each rank, scan the filtered entries that are not taken yet, keep the first one found, and replace it only on a strictly higher rating. Mark the winner as taken and write its line.
One new situation appears: a product can have fewer than k brands, or none. Then some rounds find nobody, and bestIndex stays at -1 after the scan. Such a round must add no line, so the marking and the line building sit inside an if (bestIndex != -1) check.
Step by step
- Create
filteredBrandsas an emptyList<string>andfilteredRatingsas an emptyList<int>. They will hold the rows that sell the target product. - Loop over every row with
ifrom 0 toproducts.Length. The sameiis valid in all three arrays. - Test the row with
if (products[i] == target). For strings,==compares the characters, so noEqualscall is needed. - Copy the row. Inside the
if, addbrands[i]tofilteredBrandsandratings[i]tofilteredRatings, in the same order, so a brand and its rating stay at the same position. - Create
usedasnew bool[filteredRatings.Count]: one flag per filtered entry, allfalse. Its length comes from the filtered list, not from the original arrays. - Create
linesas an emptyList<string>for the finished lines. - Write the rank loop with
rankfrom 1 up to and includingk, and createbestIndexat -1 inside it so each round starts with nobody chosen. - Write the inner loop over every position of
filteredRatings. A position is a candidate when!used[i]. Inside thatif, a second one testsbestIndex == -1 || filteredRatings[i] > filteredRatings[bestIndex], and when true it setsbestIndex = i. - Check that someone was found with
if (bestIndex != -1)after the inner loop. Inside it, setused[bestIndex] = true, then add the line built fromrank,filteredBrands[bestIndex]andfilteredRatings[bestIndex]. - Print after the loops with
string.Join("\n", lines)insideConsole.WriteLine.
The solution in C#
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 List<string>();
List<int> filteredRatings = new List<int>();
for (int i = 0; i < products.Length; i++) {
if (products[i] == target) {
filteredBrands.Add(brands[i]);
filteredRatings.Add(ratings[i]);
}
}
bool[] used = new bool[filteredRatings.Count];
List<string> lines = new List<string>();
for (int rank = 1; rank <= k; rank++) {
int bestIndex = -1;
for (int i = 0; i < filteredRatings.Count; i++) {
if (!used[i]) {
if (bestIndex == -1 || filteredRatings[i] > filteredRatings[bestIndex]) {
bestIndex = i;
}
}
}
if (bestIndex != -1) {
used[bestIndex] = true;
lines.Add(rank + ". " + filteredBrands[bestIndex] + " (" + filteredRatings[bestIndex] + ")");
}
}
Console.WriteLine(string.Join("\n", lines));
Details worth knowing:
- Arrays have
Length, lists haveCount. The loop over the catalog usesproducts.Length, and the loop over the filtered data usesfilteredRatings.Count. Swapping them is a compile error. - List indexing.
filteredRatings[i]reads a list just like an array, and an invalid index throws anArgumentOutOfRangeException, where an array throws anIndexOutOfRangeException. - String equality.
==on twostringvalues compares contents, soproducts[i] == targetis true for any text spelled the same. It is case-sensitive:"Laptop" == "laptop"isfalse. - The index shift. Position
iin the filtered lists is not positioniin the catalog. NeoByte sits at position 2 ofbrandsbut at position 1 offilteredBrands. The search must use only filtered positions. - The variable
iis reused. The filter loop and the inner search loop both declareint i. That is legal because eachilives only inside its own loop, and the two loops are not nested. Two loops nested inside one another cannot reuse the name, though, which is why the outer loop is calledrank. string.Joinwith no lines returns an empty string, soConsole.WriteLineprints a blank line.
Complexity
Let n be the number of rows and m the number of rows that match the target, so m is at most n.
Time: O(n + k * m). The filter looks at every row once. Each of the k rounds then scans m filtered entries. In the worst case all rows match and k is as large as n, which makes O(n^2).
Space: O(n). The filtered lists and the used array together hold up to m entries each, and lines holds at most min(k, m) strings.
Edge cases and common mistakes
- Fewer matches than
k. For"Tablet"withk = 3only one row matches, and the output is the single line1. Quantum (3). The two extra rounds find nobody and add nothing. - No match at all. For
"Camera",filteredRatingsis empty, every round finds nobody, and the program prints one blank line without throwing. A spelling difference such as"laptop"gives the same result. - Ties. For
"Laptop"withk = 3, the third line is3. AlphaTech (4), after TechPro. For"Phone"withk = 2the output is1. MegaCorp (5)and2. Zenith (4). - Dropping the
bestIndex != -1check.used[-1]would throw anIndexOutOfRangeExceptionas soon as a round finds nobody. - Sizing
usedfromratings. The flags are indexed by filtered position, so make the array as long as the filtered data,filteredRatings.Count. Mixing up the catalog's positions and the filtered positions is how wrong brands get printed. - Printing the ranks from the original positions. The rank is the loop counter, not an array index.
Testing
"Laptop"withk = 2prints1. NeoByte (5)and2. TechPro (4)."Laptop"withk = 5prints three lines: NeoByte (5), TechPro (4) and AlphaTech (4)."Phone"withk = 2prints1. MegaCorp (5)and2. Zenith (4)."Tablet"withk = 3prints1. Quantum (3)."Camera"withk = 2prints a blank line.
The next version builds on this one.
