Problem overview
The catalog now covers several products. Three parallel arrays describe it: row i is one product, products[i], sold by the brand brands[i], with the rating ratings[i]. The constant target names the product of interest, and k says how many brands to list.
The program first keeps only the rows whose product equals target, then prints the top k of those brands by rating, best first, as rank. Brand (rating). Ties go to the entry listed first. If fewer than k rows match, only the existing brands are listed, with no extra lines.
In the starting data the target is "Laptop" and k is 2. The laptop rows are TechPro (4), NeoByte (5) and AlphaTech (4), so the output is:
1. NeoByte (5)
2. TechPro (4)
Approach: filter first, then repeat the search
The work splits into two stages.
Filtering. One loop over the whole catalog copies the brand and the rating of each matching row into two new arrays, filteredBrands and filteredRatings. The two arrays are filled together, in the original order, so a brand and its rating stay at the same position.
Ranking. After filtering, the problem is the one from the previous version, on shorter arrays. For each rank from 1 to k the program scans every filtered entry, skips the ones already used, and keeps the position of the best rating so far. A strict "greater than" keeps the earlier entry on a tie. It then marks the winner as used and adds a line.
The one new condition is for matches running out. If only two rows match and k is 3, the third round finds nothing, and bestIndex stays at -1. The program adds a line only when it found a brand.
Tracing the starting data: the filter keeps rows 0, 2 and 5, so filteredBrands is ["TechPro", "NeoByte", "AlphaTech"] and filteredRatings is [4, 5, 4]. Round 1 picks NeoByte (5). Round 2 skips NeoByte. TechPro (4) is reached first, and AlphaTech's 4 isn't strictly greater, so TechPro wins the second place.
Step by step
- Create the filtered brands. An empty
string[]namedfilteredBrands. - Create the filtered ratings. An empty
number[]namedfilteredRatings. Both arrays will stay in step, position by position. - Loop over the catalog. A
forloop whereitakes each position ofproducts. The three starting arrays line up, so rowiis one product with its brand and rating. - Test the product. Inside the loop, an
ifforproducts[i] === target. Other rows are skipped. - Copy the brand, with
push, intofilteredBrands. - Copy the rating the same way into
filteredRatings, so the pair stays aligned. - Create the flags. A
boolean[]namedused, with afalsefor each filtered rating. The search runs on the filtered arrays, so the flags are as long as they are. - Create the output list. An empty
string[]namedlines. - Write the rank loop, with
rankfrom 1 up to and includingk. - Reset the best. Inside it,
bestIndexstarts at-1. - Write the inner loop over every position of
filteredRatings. - Skip used entries with an
ifonused[i]being false. - Compare. Inside it, a second
if: nothing found yet, or a strictly higher rating. - Remember the position by setting
bestIndextoi. - Check that something was found. After the inner loop, an
ifforbestIndexnot equal to-1. - Mark the winner by setting
used[bestIndex]totrue. - Add the line to
lineswithpush: the rank, a dot and a space, the brand's name and the rating in parentheses, all from the filtered arrays. - Print. After the loop,
lines.join("\n")insideconsole.log.
The solution in TypeScript
const products: string[] = ["Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"];
const brands: string[] = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"];
const ratings: number[] = [4, 5, 5, 3, 4, 4];
const target: string = "Laptop";
const k: number = 2;
const filteredBrands: string[] = [];
const filteredRatings: number[] = [];
for (let i = 0; i < products.length; i++) {
if (products[i] === target) {
filteredBrands.push(brands[i]);
filteredRatings.push(ratings[i]);
}
}
const used: boolean[] = new Array(filteredRatings.length).fill(false);
const lines: string[] = [];
for (let rank = 1; rank <= k; rank++) {
let bestIndex: number = -1;
for (let i = 0; i < filteredRatings.length; i++) {
if (!used[i]) {
if (bestIndex === -1 || filteredRatings[i] > filteredRatings[bestIndex]) {
bestIndex = i;
}
}
}
if (bestIndex != -1) {
used[bestIndex] = true;
lines.push(rank + ". " + filteredBrands[bestIndex] + " (" + filteredRatings[bestIndex] + ")");
}
}
console.log(lines.join("\n"));
Details worth knowing:
===on strings.products[i] === targetcompares the text itself, and it is case-sensitive:"Laptop"and"laptop"are different values.push. It adds a value at the end of an array and changes the array in place. That is whyfilteredBrandsandfilteredRatingscan beconst: the variable never points to a different array.- Loop variable names. The two
ivariables belong to separate loops, so they don't clash. !=. The solution compares with!=, which for two numbers behaves the same as!==.- Joining the lines. If
linesis empty,join("\n")returns an empty string, andconsole.logprints an empty line.
Complexity
Time: O(n + k * m), where n is the number of catalog rows and m the number of rows that match. Filtering is one pass over n rows. Ranking is k scans of m entries.
Space: O(m). The filtered arrays and used each hold m entries, and lines holds at most min(k, m) strings.
Edge cases and common mistakes
- Fewer matches than
k. Withk = 5and"Laptop", only three rows match, and the program prints three lines: NeoByte (5), TechPro (4) and AlphaTech (4). A target with one row works too:"Tablet"withk = 3prints only1. Quantum (3). - Removing the check on
bestIndex. Withk = 5and the laptop rows, the program would also print4. undefined (undefined)and5. undefined (undefined). Reading position-1of an array givesundefinedand no error. - No matching rows. A target such as
"Camera"prints one empty line, since there are no lines to join. A target in a different case, such as"laptop", behaves the same way, because the comparison is case-sensitive. - Another product. With
"Phone"andk = 2the output is1. MegaCorp (5)and2. Zenith (4). - Mixing up the arrays. The ranking must read
filteredBrandsandfilteredRatings. Usingbrandsorratingsinside it would index the full catalog with positions that belong to the filtered arrays. - Copying only one of the two values. If the filter pushes the brand but not the rating, the arrays go out of step and the ratings no longer belong to the brands.
Testing
- The starting data prints
1. NeoByte (5)and2. TechPro (4). "Laptop"withk = 5prints NeoByte (5), TechPro (4) and AlphaTech (4), numbered 1 to 3."Phone"withk = 2prints1. MegaCorp (5)and2. Zenith (4)."Tablet"withk = 3prints1. Quantum (3).
