Problem overview
Two parallel arrays describe the brands: ratings[i] is the rating of brands[i]. The constant k says how many brands to show. The program prints the top k brands by rating, best first, one per line, in the form rank. Brand (rating), with ranks starting at 1.
When two brands have the same rating, the one listed first ranks higher. In the starting data MegaCorp and NeoByte both have a rating of 5, and so do TechPro and Zenith with 4. With k = 3 the output is:
1. MegaCorp (5)
2. NeoByte (5)
3. TechPro (4)
The value of k is never larger than the number of brands.
Approach: find the best, mark it, search again
The previous version found the single best brand with a running maximum. This version repeats that search k times. Repeating it unchanged would give MegaCorp every time, so each winner is marked as taken and the next round skips it.
The marks live in a boolean array, used, with one entry per brand, all false to begin with. After a round picks a winner, that entry becomes true.
Each round is a nested pair of loops: the outer loop is the round, the inner loop is the scan over all the brands. The scan keeps bestIndex, the position of the best brand found so far in this round, starting at -1. Since -1 is not a position, it means that nothing has been found yet. A brand is a candidate only if it is not used, and it becomes the new best when nothing has been found or its rating is strictly higher than the best one's. Strictly higher gives the tie rule: the earlier brand keeps the lead.
The results are collected in an array of strings, lines, and printed once at the end, joined with newlines.
For the starting data, the three rounds go like this:
| Round (rank) | Winner | Why |
|---|---|---|
| 1 | MegaCorp (5) | 5 is the highest rating, and MegaCorp is listed before NeoByte |
| 2 | NeoByte (5) | MegaCorp is used, so NeoByte is the best of the rest |
| 3 | TechPro (4) | Among the rating-4 brands, TechPro is listed first |
Step by step
- Create the flags.
usedis aboolean[]withfalsefor every rating.used[i]says whether brandihas already won a place. - Create the output list.
linesis an emptystring[]. The lines arrive one per round. - Write the outer loop.
rankruns from 1 up to and includingk. It is also the number printed in front of the brand, so it starts at 1. - Reset the best. Inside the outer loop,
bestIndexstarts at-1, so every round starts over. - Write the inner loop.
itakes every position ofratings, because each round looks at all the brands again. - Skip the used brands. An
iflets only brands withused[i]false through. - Compare. Inside it, a second
if:bestIndexis-1, orratings[i]is strictly greater thanratings[bestIndex]. - Remember the brand. Set
bestIndextoi. - Mark the winner. After the inner loop, set
used[bestIndex]totrue. - Build the line.
pushthe rank,". ", the brand's name, and the rating in parentheses ontolines. - Print. After the loop,
lines.join("\n")turns the array into one string with a newline between lines, andconsole.logprints it.
The solution in TypeScript
const brands: string[] = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
const ratings: number[] = [4, 5, 3, 5, 4];
const k: number = 3;
const used: boolean[] = new Array(ratings.length).fill(false);
const lines: string[] = [];
for (let rank = 1; rank <= k; rank++) {
let bestIndex: number = -1;
for (let i = 0; i < ratings.length; i++) {
if (!used[i]) {
if (bestIndex === -1 || ratings[i] > ratings[bestIndex]) {
bestIndex = i;
}
}
}
used[bestIndex] = true;
lines.push(rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");
}
console.log(lines.join("\n"));
Details worth knowing:
new Array(n).fill(false).new Array(n)creates an array of lengthnwith empty slots, andfill(false)sets each slot tofalse. Theboolean[]annotation is erased when the code compiles to JavaScript.join("\n"). It puts the separator between elements only, so the output has no trailing newline. Without an argument,join()uses a comma:["1. A (5)", "2. B (4)"].join()gives1. A (5),2. B (4).- Building text with
+.rank + ". "starts with a number, but the second operand is a string, so+concatenates and the number becomes text. - Nested ifs. The two
ifs could be merged with&&. Nesting them keeps each condition simple.
Complexity
Time: O(k * n). Each of the k rounds scans all n brands. When k is small, that is close to linear. When k equals n, it becomes O(n²), where sorting would be O(n log n).
Space: O(n). The used array has n entries, and lines holds up to k strings.
Edge cases and common mistakes
- Ties. With
>=in place of>, the later brand replaces the earlier one, and the starting data prints NeoByte before MegaCorp. When all five ratings are 3 andk = 5, the strict version lists the brands in their original order: TechPro, MegaCorp, Quantum, NeoByte, Zenith. - Forgetting to mark the winner. Without
used[bestIndex] = true, every round finds the same brand, and the output is three lines ofMegaCorp (5)with ranks 1, 2 and 3. - The rank range. With
rank < kthe loop makes one round too few: fork = 3only two lines print. - Extreme values of
k.k = 1prints only MegaCorp.k = 5prints all five brands, ending with Quantum (3). The lesson promiseskis not larger than the number of brands. Withk = 6the program doesn't crash, but prints a sixth line,6. undefined (undefined), because no brand is left to find.
Testing
- The starting data with
k = 3prints1. MegaCorp (5),2. NeoByte (5)and3. TechPro (4). k = 1prints1. MegaCorp (5).k = 5prints MegaCorp, NeoByte, TechPro, Zenith and Quantum, in that order, with ratings 5, 5, 4, 4 and 3.
