Start learning free

LESSON 187 OF 291 · LOOPING OVER ARRAY INDICES

Top K Brands V3 in Kotlin: Scanning Parallel Arrays for the Best

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 = arrayOf("TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith")
        val ratings = intArrayOf(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 in 1 until ratings.size) { and compare each rating with the best one so far.

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

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

        var bestIndex = 0
        for (i in 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

    KOTLIN · LOOPING OVER ARRAY INDICES

    Top K Brands V3 in Kotlin, explained

    Problem overview

    Many brands now sell the same product. The data is stored in two parallel arrays: ratings[i] is the rating of brands[i]. The program finds the highest-rated brand by scanning the arrays with a loop and prints it in the form 1. Brand (rating).

    The starter code has:

    indexbrandrating
    0TechPro4
    1MegaCorp5
    2Quantum3
    3NeoByte5
    4Zenith4

    The highest rating is 5, shared by MegaCorp and NeoByte. If brands tie for the top rating, the one listed first wins, so the output is:

    1. MegaCorp (5)
    

    Approach

    Version 2 compared two brands with an if/else, which can't scale to any number of brands. A loop can. Keep the position of the best brand found so far, in bestIndex, and check every other brand against it. When one has a strictly higher rating, it becomes the new best.

    Storing the position, not the rating, is the key choice. One position gives the brand and the rating, because the two arrays line up. So the program doesn't need separate variables for the best name and the best rating, as the previous version did.

    Before any comparison the first brand is the only one seen, so it is the best so far, and bestIndex starts at 0. The loop starts at position 1, because comparing the first brand with itself would do nothing.

    Step by step

    1. Create bestIndex as a var set to 0, since the loop will change it.
    2. Write the loop. for (i in 1 until ratings.size) makes i run from 1 up to, but not including, the number of ratings. It visits the same position in both arrays.
    3. Test the current brand. Inside the loop, write an if that checks ratings[i] > ratings[bestIndex]. Strictly greater means that on a tie the earlier brand keeps the lead.
    4. Update the best. Inside the if, set bestIndex = i.
    5. Print after the loop. Join "1. ", brands[bestIndex], " (", ratings[bestIndex] and ")".

    The solution in Kotlin

            val brands = arrayOf("TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith")
            val ratings = intArrayOf(4, 5, 3, 5, 4)
    
            var bestIndex = 0
            for (i in 1 until ratings.size) {
                if (ratings[i] > ratings[bestIndex]) {
                    bestIndex = i
                }
            }
            println("1. " + brands[bestIndex] + " (" + ratings[bestIndex] + ")")
    

    How the loop runs

    • Start: bestIndex is 0 (TechPro, rating 4).
    • i = 1: rating 5 is greater than 4, so bestIndex becomes 1.
    • i = 2: rating 3 is not greater than 5.
    • i = 3: rating 5 is not strictly greater than 5, so bestIndex stays 1. This is why MegaCorp beats NeoByte.
    • i = 4: rating 4 is not greater than 5.

    The loop ends with bestIndex equal to 1, and the program prints 1. MegaCorp (5).

    Kotlin details

    • Two array types. arrayOf(...) makes an Array<String>, and intArrayOf(...) makes an IntArray of primitive ints. Both are read with [i] and have a size.
    • until excludes the end. 1 until ratings.size is 1, 2, 3, 4 for five ratings. The range 1..ratings.size includes 5, and ratings[5] throws ArrayIndexOutOfBoundsException.
    • The loop variable. i is declared by the for itself and is a read-only val. You can't assign to it inside the loop, which is why the program copies it into bestIndex.
    • Brackets in the output. brands[bestIndex] and ratings[bestIndex] sit in the middle of a + chain. The String on the left makes + convert the Int rating to text.

    Complexity

    The loop checks each brand once, so the time is O(n) for n brands. The extra space is O(1): a single index.

    Edge cases and common mistakes

    • Ties. With >=, the later brand would replace the earlier one on every tie, and the program would print NeoByte. The strict > is what the task requires.
    • The best is first. With ratings 5, 3, 4 for brands A, B, C, nothing beats position 0, and the output is 1. A (5).
    • The best is last. With ratings 2, 3, 5 the index moves at positions 1 and 2, and the output is 1. C (5).
    • A single brand. With one brand, 1 until 1 is empty and the loop never runs. The program prints that brand: ratings of 2 for one brand named Only gives 1. Only (2).
    • Remembering the rating, not the position. If you keep only the best rating, you can print the rating but can't tell which brand it belongs to.
    • Going past the end. Use until with ratings.size.

    Testing

    brands, ratingsoutput
    the lesson's five brands, 4 5 3 5 41. MegaCorp (5)
    A B C, 5 3 41. A (5)
    A B C, 2 3 51. C (5)
    Only, 21. Only (2)
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free