Start learning free

LESSON 256 OF 289 · NESTED LOOPS

Top K Brands V6 in TypeScript: Ranking with a Tie-Break by Reviews

Practice Read the full explanation

Rank the top k brands by rating, breaking ties with the review count. This builds on v4's repeated search (not on v5: there is no filtering here); only the comparison gets a second criterion.

You start with:

const brands: string[] = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"];
const ratings: number[] = [4, 5, 5, 3, 4];
const reviews: number[] = [200, 150, 500, 100, 300];
const k: number = 3;

Build:

1. NeoByte (5, 500)
2. MegaCorp (5, 150)
3. Zenith (4, 300)

Rules:

  • Rating decides first: the higher rating wins.
  • If two brands have the same rating, the one with more reviews wins.
  • If rating and reviews are both equal, the one listed first wins (the test data has no such pair, but your code must follow the rule).
  • k is never larger than the number of brands.
  • Each line is "rank. Brand (rating, reviews)", starting at rank 1.
  • Print the lines, one per line, with console.log(...).

Start from v4: the same const used: boolean[] = new Array(ratings.length).fill(false); and const lines: string[] = [];, the same two loops. Only the comparison inside the inner loop changes.

Use a chain (if / else if / else if): no candidate yet, take this one; else a higher rating, take this one; else the same rating and more reviews, take this one.

const brands: string[] = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"];
const ratings: number[] = [4, 5, 5, 3, 4];
const reviews: number[] = [200, 150, 500, 100, 300];
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) {
                bestIndex = i;
            }
            else if (ratings[i] > ratings[bestIndex]) {
                bestIndex = i;
            }
            else if (ratings[i] === ratings[bestIndex] && reviews[i] > reviews[bestIndex]) {
                bestIndex = i;
            }
        }
    }
    used[bestIndex] = true;
    lines.push(rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ", " + reviews[bestIndex] + ")");
}
console.log(lines.join("\n"));

STEP 1 OF 12
    Ctrl + Enter to check

    TYPESCRIPT · NESTED LOOPS

    Top K Brands V6 in TypeScript, explained

    Problem overview

    Three parallel arrays describe the brands: ratings[i] and reviews[i] are the rating and the review count of brands[i]. The program prints the top k brands, best first, one per line, in the form rank. Brand (rating, reviews), with ranks starting at 1.

    Rating decides first. If two brands have the same rating, the one with more reviews wins. If both are equal, the one listed first wins. The constant k is never larger than the number of brands.

    In the starting data NeoByte and MegaCorp both have a rating of 5, with 500 and 150 reviews, and TechPro and Zenith both have a rating of 4. With k = 3 the output is:

    1. NeoByte (5, 500)
    2. MegaCorp (5, 150)
    3. Zenith (4, 300)
    

    Approach: the same repeated search, a second comparison

    The structure is the repeated search from version 4: for each rank, scan all the brands that are not used yet, keep the position of the best one, mark it as used and add a line. Only the question "is this brand better than the current best?" changes. This version doesn't filter anything.

    That question now has three cases, checked in order:

    1. Nothing has been found in this round yet (bestIndex is -1). This brand is the best so far, because it has nobody to beat.
    2. Otherwise, its rating is higher than the best one's. A higher rating wins before the reviews count at all.
    3. Otherwise, the ratings are equal and this brand has more reviews. Reviews only break a tie, so both parts of the condition must hold.

    If none of the three holds, the current best stays. That includes a brand with exactly the same rating and review count: it isn't strictly better, so the earlier one keeps the lead, which is the third rule.

    The chain is written with else if, so a brand triggers at most one case, and the order of the cases matters.

    The second case needs a rating higher than the best, and the third needs an equal rating, so the two never both hold for the same brand.

    In the starting data, the first round picks NeoByte: its rating of 5 ties MegaCorp's, and 500 reviews beat 150. In the second round NeoByte is used, so MegaCorp is the best rating that is left. In the third round the two 5s are gone, and among the 4s Zenith's 300 reviews beat TechPro's 200.

    Step by step

    1. Create the flags. A boolean[] named used, with false for each rating.
    2. Create the output list. An empty string[] named lines.
    3. Write the rank loop. rank goes from 1 up to and including k. It is also the number printed in front of the brand.
    4. Reset the best. Inside it, bestIndex starts at -1, so each round starts over.
    5. Write the inner loop, where i takes every position of ratings.
    6. Skip used brands with an if on used[i] being false.
    7. First case. Inside it, if bestIndex is -1, set it to i.
    8. Second case, an else if: ratings[i] is greater than ratings[bestIndex]. Set bestIndex to i.
    9. Third case, another else if: the ratings are equal and reviews[i] is greater than reviews[bestIndex]. Set bestIndex to i.
    10. Mark the winner. After the inner loop, set used[bestIndex] to true.
    11. Add the line. push the rank, a dot and a space, the name, then the rating and the review count in parentheses, separated by a comma and a space.
    12. Print lines.join("\n") with console.log after the loop.

    The solution in TypeScript

    const brands: string[] = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"];
    const ratings: number[] = [4, 5, 5, 3, 4];
    const reviews: number[] = [200, 150, 500, 100, 300];
    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) {
                    bestIndex = i;
                }
                else if (ratings[i] > ratings[bestIndex]) {
                    bestIndex = i;
                }
                else if (ratings[i] === ratings[bestIndex] && reviews[i] > reviews[bestIndex]) {
                    bestIndex = i;
                }
            }
        }
        used[bestIndex] = true;
        lines.push(rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ", " + reviews[bestIndex] + ")");
    }
    console.log(lines.join("\n"));
    

    Details worth knowing:

    • === with numbers. ratings[i] === ratings[bestIndex] compares two numbers without any conversion.
    • && in the third case. Both sides must be true: same rating, and strictly more reviews.
    • else on a new line. The solution puts else if on its own line after the closing brace. TypeScript doesn't mind, because whitespace between the brace and else is ignored.
    • Parallel arrays. The three arrays are tied together only by position. The same index reads the name, the rating and the review count of one brand.
    • Types are erased. The annotations help the compiler and don't exist in the JavaScript that runs.

    Complexity

    Time: O(k * n). Each of the k rounds scans all n brands, and each comparison takes constant time. For k equal to n this is O(n²).

    Space: O(n). The used array has n entries, and lines holds k strings.

    Edge cases and common mistakes

    • Dropping the rating test from the third case. If the third condition is only reviews[i] > reviews[bestIndex], a brand with a lower rating can beat a better one just because it has more reviews. For the starting data and k = 3 the output becomes NeoByte (5, 500), Zenith (4, 300), then MegaCorp (5, 150), which is wrong.
    • Using || to join the rating and the review count. A single condition such as "higher rating, or more reviews" gives the same wrong order as above.
    • Equal rating and equal reviews. With reviews of [200, 150, 150, 100, 300], MegaCorp and NeoByte tie on both numbers. The output is MegaCorp (5, 150), NeoByte (5, 150) and Zenith (4, 300): the one listed first wins. If the third case used >=, NeoByte would come first.
    • The tie-break going the other way. With reviews of [200, 500, 150, 100, 300], MegaCorp has 500 reviews and NeoByte only 150, so MegaCorp is first, with 1. MegaCorp (5, 500) and 2. NeoByte (5, 150). The order in the arrays only matters when both numbers are equal.
    • Forgetting to mark the winner. Without used[bestIndex] = true, every round returns the same brand.
    • Extreme values of k. k = 1 prints only 1. NeoByte (5, 500). With k = 5 all brands are printed, and the last two lines are 4. TechPro (4, 200) and 5. Quantum (3, 100).

    Testing

    • The starting data with k = 3 prints 1. NeoByte (5, 500), 2. MegaCorp (5, 150) and 3. Zenith (4, 300).
    • k = 1 prints 1. NeoByte (5, 500).
    • k = 5 prints NeoByte, MegaCorp, Zenith, TechPro and Quantum, in that order.
    • Reviews [200, 500, 150, 100, 300] with k = 3 print 1. MegaCorp (5, 500), 2. NeoByte (5, 150) and 3. Zenith (4, 300).
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free