Start learning free

LESSON 187 OF 289 · LOOPING OVER ARRAY INDICES

Top K Brands V3 in TypeScript: Best in an Array with a Loop

Practice Read the full explanation

Many brands sell the same product, stored in two parallel arrays: ratings[i] is the rating of brands[i]. Find the highest-rated brand by scanning with a loop.

You start with:

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

Build:

1. MegaCorp (5)

Rules:

  • Keep the position of the best brand so far in bestIndex, starting at 0, and scan the positions from 1 to the end with a loop.
  • Update bestIndex only on a strictly higher rating. If two brands share the top rating, the one listed first wins (MegaCorp at position 1, not NeoByte at position 3).
  • Format the winner as "1. Brand (rating)" and print it with console.log(...).

Walk the positions with for (let i: number = 1; i < ratings.length; i++) { and compare each rating with the best one so far.

TypeScript turns the number into text for you when you join it to a string with +.

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

let bestIndex: number = 0;
for (let i: number = 1; i < ratings.length; i++) {
    if (ratings[i] > ratings[bestIndex]) {
        bestIndex = i;
    }
}
console.log("1. " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");

STEP 1 OF 5
    Ctrl + Enter to check

    TYPESCRIPT · LOOPING OVER ARRAY INDICES

    Top K Brands V3 in TypeScript, explained

    Problem overview

    Many brands sell the same product. The data is two parallel arrays: ratings[i] is the rating of brands[i]. The program must find the highest-rated brand and print it as 1. Brand (rating). If several brands share the top rating, the one listed first wins.

    In the starter data, MegaCorp (position 1) and NeoByte (position 3) both have a rating of 5, and MegaCorp is listed first:

    1. MegaCorp (5)

    Approach

    The method is a running maximum, scanned with a loop. Keep one variable, bestIndex, with the position of the best brand so far, starting at 0, and look at every other position in turn. When a rating is strictly higher than the one at bestIndex, move bestIndex there.

    The program stores a position instead of the rating itself, because one position gives both pieces of the output. brands[bestIndex] is the name and ratings[bestIndex] is the rating, since the arrays line up.

    Tracing the starter data: bestIndex starts at 0 (rating 4). Position 1 has 5, which is higher, so bestIndex becomes 1. Position 2 has 3, no change. Position 3 has 5, which is not strictly higher than 5, so MegaCorp keeps the lead. Position 4 has 4, no change. The loop ends with bestIndex at 1.

    Step by step

    1. Create bestIndex at 0 with let, since it will change. Until a better brand shows up, the first one is the best.
    2. Write the loop. i starts at 1 and goes up by one while i < ratings.length. Position 0 is already the best so far, so the scan begins at 1. The same i addresses both arrays.
    3. Compare inside the loop. An if checks whether ratings[i] is strictly greater than ratings[bestIndex]. Strictly greater means a tie leaves the earlier brand in front, which is why MegaCorp beats NeoByte.
    4. Update the best. Inside the if, set bestIndex to i.
    5. Print the winner after the loop: "1. ", brands[bestIndex], " (", ratings[bestIndex] and ")", joined with +.

    The solution in TypeScript

    const brands: string[] = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
    const ratings: number[] = [4, 5, 3, 5, 4];
    
    let bestIndex: number = 0;
    for (let i: number = 1; i < ratings.length; i++) {
        if (ratings[i] > ratings[bestIndex]) {
            bestIndex = i;
        }
    }
    console.log("1. " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");
    

    Details specific to TypeScript:

    • Array annotations. string[] and number[] describe the arrays for the compiler. They are erased in the JavaScript that runs, so the arrays are ordinary JavaScript arrays.
    • Loop scope. let i in the for header exists only inside the loop. i++ adds one after each pass.
    • Number to text. In "1. " + brands[bestIndex] + " (" + ratings[bestIndex] + ")" every + concatenates, since a string is always on the left. The rating becomes text without a conversion call.

    Complexity

    Time: O(n). The loop visits each position once and does constant work per position.

    Space: O(1). The program stores one index, however long the arrays are.

    Edge cases and common mistakes

    • Ties. With >= in place of >, the output of the starter data changes to 1. NeoByte (5), because the later brand replaces the earlier one. If all ratings are 3, the strict version prints 1. TechPro (3), the first brand.
    • The best brand is first or last. With ratings [5, 4, 3, 2, 1] the output is 1. TechPro (5), and with [1, 2, 3, 4, 5] it is 1. Zenith (5).
    • Starting the loop at 0. The output stays 1. MegaCorp (5), since comparing position 0 with itself changes nothing. It is one extra pass.
    • Tracking the rating only. A running maximum of the rating tells you how high it is but not which brand has it. The index carries both.

    Testing

    • Ratings [4, 5, 3, 5, 4] print 1. MegaCorp (5).
    • Ratings [5, 4, 3, 2, 1] print 1. TechPro (5).
    • Ratings [1, 2, 3, 4, 5] print 1. Zenith (5).
    • Ratings [3, 3, 3, 3, 3] print 1. TechPro (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