Start learning free

LESSON 187 OF 291 · LOOPING OVER ARRAY INDICES

Top K Brands V3 in Scala: Max in an Array

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:

        val brands = Array("TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith")
        val ratings = Array(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 println(...).

Walk the positions with for (i <- 1 until ratings.size) { and compare each rating with the best one so far.

Scala's + on a String and an Int converts the number to text for you.

        val brands = Array("TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith")
        val ratings = Array(4, 5, 3, 5, 4)

        var bestIndex = 0
        for (i <- 1 until ratings.size) {
            if (ratings(i) > ratings(bestIndex)) {
                bestIndex = i
            }
        }
        println("1. " + brands(bestIndex) + " (" + ratings(bestIndex) + ")")

STEP 1 OF 5
    Ctrl + Enter to check

    SCALA · LOOPING OVER ARRAY INDICES

    Top K Brands V3 in Scala, explained

    Problem overview

    Several brands sell the same product. Their names are in the array brands and their ratings in the array ratings, and ratings(i) is the rating of brands(i). The program must find the highest-rated brand and print it as one ranked line, 1. Brand (rating). If two brands share the top rating, the one listed first wins.

    The starter data has five brands:

    brands:  TechPro  MegaCorp  Quantum  NeoByte  Zenith
    ratings:    4        5         3        5        4
    

    The top rating is 5, which both MegaCorp (position 1) and NeoByte (position 3) have. MegaCorp is listed first, so the output is:

    1. MegaCorp (5)
    

    The previous version printed the entry for a single brand. Now the brand has to be chosen from a list.

    Approach: keep the position of the best so far

    Scan the arrays once from left to right. Keep the position of the best brand seen so far, and update it only when a later brand has a strictly higher rating. Start by assuming position 0 is the best, since at the start it is the only brand seen.

    The program stores a position rather than the rating itself because one position gives both facts: brands(bestIndex) is the name and ratings(bestIndex) is the rating. If it stored only the best rating, it would have no way to find the matching name afterwards.

    The tie rule decides the comparison. A strict > means that a brand with the same rating as the current best doesn't replace it, so the earlier brand stays in front. With >=, NeoByte would take the lead from MegaCorp.

    Step by step

    1. Create bestIndex as a var set to 0. It changes during the scan, so it can't be a val.
    2. Write the loop header, for (i <- 1 until ratings.size). The variable i takes the positions 1 to 4. Position 0 is already the best so far, so the scan begins at 1. Write the closing brace immediately.
    3. Write the if inside the loop. It compares ratings(i) with ratings(bestIndex), strictly greater.
    4. Assign i to bestIndex inside the if. This brand is the new leader.
    5. Print the winner after the loop. Join the rank "1. ", the brand at bestIndex, " (", the rating at bestIndex and ")" with +.

    The solution in Scala

            val brands = Array("TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith")
            val ratings = Array(4, 5, 3, 5, 4)
    
            var bestIndex = 0
            for (i <- 1 until ratings.size) {
                if (ratings(i) > ratings(bestIndex)) {
                    bestIndex = i
                }
            }
            println("1. " + brands(bestIndex) + " (" + ratings(bestIndex) + ")")
    

    Scala details worth knowing:

    • Array elements use parentheses. Scala writes ratings(i). Square brackets in Scala are for type parameters, such as Array[Int].
    • 1 until n excludes n. For five ratings it produces 1, 2, 3 and 4. 1 to ratings.size would include 5, which is past the end of the array, and the last round would throw an ArrayIndexOutOfBoundsException.
    • The loop variable can't be assigned. Inside the for, i is a fresh val each round. That is why bestIndex is declared outside the loop as a var and assigned from i.
    • String plus Int. + on a String converts the number to text, so " (" + ratings(bestIndex) + ")" needs no explicit conversion. The order matters: the left-hand side of the first + is a string, so every + after it joins text.

    Following the loop

    The variable bestIndex starts at 0, with rating 4.

    iBrandRatingBeats the best (strictly)?bestIndex afterwards
    1MegaCorp5yes, 5 > 41
    2Quantum3no1
    3NeoByte5no, 5 is not > 51
    4Zenith4no1

    Complexity

    Time: O(n), where n is the number of brands: the loop visits each brand once and does constant work. Space: O(1), because the program keeps one extra index.

    Testing

    With the same brands and different ratings:

    RatingsOutput
    4, 5, 3, 5, 41. MegaCorp (5)
    4, 4, 3, 5, 51. NeoByte (5)
    5, 5, 5, 5, 51. TechPro (5)
    1, 2, 3, 4, 51. Zenith (5)

    A single brand, Array("Only") with ratings Array(2), prints 1. Only (2): the loop range is empty and position 0 stays the best.

    Edge cases and common mistakes

    • Using >=. The last brand with the top rating would win instead of the first. In the first row, NeoByte would be printed.
    • Storing the rating instead of the position. The name could no longer be found.
    • Everyone tied. With all ratings equal, nothing is ever replaced and the first brand is printed, as in the third row.
    • The best brand last. The loop reaches position 4 in the last row and updates there, so the final position is covered.
    • Empty arrays. This version assumes at least one brand. With empty arrays, reading position 0 throws an exception.
    • Arrays of different lengths. The loop uses the length of ratings. If brands is shorter, reading brands(bestIndex) can go past its end.

    Key takeaways

    • Parallel arrays share indexes, so one position identifies a brand and its rating.
    • Updating only on a strictly higher value keeps the first of several ties.
    • Start from position 0 and loop from 1.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free