Start learning free

LESSON 254 OF 289 · NESTED LOOPS

Top K Brands V4 in TypeScript: Repeated Search with Nested Loops

Practice Read the full explanation

Show the top k brands by rating. This is v3's search, repeated k times: find the best brand, mark it as taken, then search again among the brands that are not taken yet, until you have k brands in rank order.

You start with:

const brands: string[] = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
const ratings: number[] = [4, 5, 3, 5, 4];
const k: number = 3;

Build:

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

Rules:

  • Repeat v3's search k times. Each round looks only at brands that are not taken yet and picks the one with the highest rating, then marks it as taken (one true/false flag per brand).
  • Ties go to the brand listed first: keep the first brand you find and replace it only on a strictly higher rating.
  • k is never larger than the number of brands.
  • Each line is "rank. Brand (rating)", starting at rank 1.
  • Print the lines, one per line, with console.log(...).

Start with the two declarations const used: boolean[] = new Array(ratings.length).fill(false); and const lines: string[] = [];. A flag tells whether that position is already taken.

Each round is v3's search: nothing found yet, scan every position, skip taken ones, keep the first candidate and replace it only on a strictly higher rating. Then mark the winner as taken and add its line.

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"));

STEP 1 OF 11
    Ctrl + Enter to check

    TYPESCRIPT · NESTED LOOPS

    Top K Brands V4 in TypeScript, explained

    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)WinnerWhy
    1MegaCorp (5)5 is the highest rating, and MegaCorp is listed before NeoByte
    2NeoByte (5)MegaCorp is used, so NeoByte is the best of the rest
    3TechPro (4)Among the rating-4 brands, TechPro is listed first

    Step by step

    1. Create the flags. used is a boolean[] with false for every rating. used[i] says whether brand i has already won a place.
    2. Create the output list. lines is an empty string[]. The lines arrive one per round.
    3. Write the outer loop. rank runs from 1 up to and including k. It is also the number printed in front of the brand, so it starts at 1.
    4. Reset the best. Inside the outer loop, bestIndex starts at -1, so every round starts over.
    5. Write the inner loop. i takes every position of ratings, because each round looks at all the brands again.
    6. Skip the used brands. An if lets only brands with used[i] false through.
    7. Compare. Inside it, a second if: bestIndex is -1, or ratings[i] is strictly greater than ratings[bestIndex].
    8. Remember the brand. Set bestIndex to i.
    9. Mark the winner. After the inner loop, set used[bestIndex] to true.
    10. Build the line. push the rank, ". ", the brand's name, and the rating in parentheses onto lines.
    11. Print. After the loop, lines.join("\n") turns the array into one string with a newline between lines, and console.log prints 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 length n with empty slots, and fill(false) sets each slot to false. The boolean[] 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() gives 1. 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 and k = 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 of MegaCorp (5) with ranks 1, 2 and 3.
    • The rank range. With rank < k the loop makes one round too few: for k = 3 only two lines print.
    • Extreme values of k. k = 1 prints only MegaCorp. k = 5 prints all five brands, ending with Quantum (3). The lesson promises k is not larger than the number of brands. With k = 6 the 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 = 3 prints 1. MegaCorp (5), 2. NeoByte (5) and 3. TechPro (4).
    • k = 1 prints 1. MegaCorp (5).
    • k = 5 prints MegaCorp, NeoByte, TechPro, Zenith and Quantum, in that order, with ratings 5, 5, 4, 4 and 3.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free