Start learning free

LESSON 254 OF 291 · NESTED LOOPS

Top K Brands V4 in Kotlin: Repeating the Search for the Top K

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:

        val brands = arrayOf("TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith")
        val ratings = intArrayOf(4, 5, 3, 5, 4)
        val k = 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 println(...).

Start with the two declarations val used = BooleanArray(ratings.size) and val lines = mutableListOf<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.

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

        val used = BooleanArray(ratings.size)
        val lines = mutableListOf<String>()
        for (rank in 1..k) {
            var bestIndex = -1
            for (i in ratings.indices) {
                if (!used[i]) {
                    if (bestIndex == -1 || ratings[i] > ratings[bestIndex]) {
                        bestIndex = i
                    }
                }
            }
            used[bestIndex] = true
            lines.add("$rank. ${brands[bestIndex]} (${ratings[bestIndex]})")
        }
        println(lines.joinToString("\n"))

STEP 1 OF 11
    Ctrl + Enter to check

    KOTLIN · NESTED LOOPS

    Top K Brands V4 in Kotlin, explained

    Problem overview

    Two parallel arrays hold the data: ratings[i] is the rating of brands[i]. The previous version found the single best brand. This version prints the top k brands in rank order, one line each, as rank. Brand (rating). Ties go to the brand listed first, and k is never larger than the number of brands.

    The starter code has five brands and k = 3:

    indexbrandrating
    0TechPro4
    1MegaCorp5
    2Quantum3
    3NeoByte5
    4Zenith4
    1. MegaCorp (5)
    2. NeoByte (5)
    3. TechPro (4)
    

    Approach

    Finding the best brand is a loop that keeps the position of the best one seen so far. To get the second best, run the same search again, but ignore the brand that already won. Do that k times and the winners come out in rank order. This is a nested loop: the outer one runs once per rank, and the inner one scans every brand.

    To ignore winners, keep one true/false flag per brand in a BooleanArray named used. A brand whose flag is true is skipped by later rounds, so no brand wins twice.

    On the lesson's data, rank 1 picks index 1 (MegaCorp, 5). Index 3 also has 5, but it isn't strictly higher, so the earlier brand stays. Rank 2 sees index 1 as used and picks index 3 (NeoByte). Rank 3 picks index 0 (TechPro, 4), the first of the two remaining brands with rating 4.

    Step by step

    1. Create used with one slot per rating. All slots start as false.
    2. Create lines, an empty mutableListOf<String>(). Each round adds one finished line to it.
    3. Loop over the ranks. for (rank in 1..k) makes rank take 1, 2, ..., k. The counter also serves as the number printed before each brand.
    4. Reset bestIndex to -1 at the start of every round. -1 is not a position, so it means "no brand found yet".
    5. Write the inner loop over the positions of ratings, so every round looks at every brand again.
    6. Skip taken brands. Only an if (!used[i]) brand can become the round's best.
    7. Compare. The brand becomes the best when nothing is found yet, or when its rating is strictly higher than the best one's. Strictly higher keeps the earlier brand on a tie.
    8. Remember the brand by setting bestIndex = i.
    9. Mark the winner after the inner loop with used[bestIndex] = true.
    10. Add the line to lines: the rank, a dot and a space, the name and the rating in parentheses.
    11. Print all the lines joined with a newline between them.

    The solution in Kotlin

            val brands = arrayOf("TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith")
            val ratings = intArrayOf(4, 5, 3, 5, 4)
            val k = 3
    
            val used = BooleanArray(ratings.size)
            val lines = mutableListOf<String>()
            for (rank in 1..k) {
                var bestIndex = -1
                for (i in ratings.indices) {
                    if (!used[i]) {
                        if (bestIndex == -1 || ratings[i] > ratings[bestIndex]) {
                            bestIndex = i
                        }
                    }
                }
                used[bestIndex] = true
                lines.add("$rank. ${brands[bestIndex]} (${ratings[bestIndex]})")
            }
            println(lines.joinToString("\n"))
    

    Kotlin details worth a look:

    • Two kinds of range. 1..k includes k, so with k = 3 it is 1, 2, 3. ratings.indices is 0..4 for five ratings, the valid positions of the array, written without the bounds.
    • String templates. In "$rank. ${brands[bestIndex]} (${ratings[bestIndex]})", a plain name after $ is enough for rank, but an expression such as an array access needs braces. The dot right after $rank is ordinary text.
    • MutableList. mutableListOf<String>() starts empty and grows with add. A list made with listOf couldn't be added to.
    • joinToString("\n"). It glues the items together with the separator between each two and none after the last, so println ends the output with a single line break. With an empty list it returns an empty string.
    • var versus val. bestIndex changes during the search, so it is a var. The arrays and the list are val: the variable never points to a different object, even though the contents change.

    Complexity

    Time: O(k * n) for n brands, since each of the k rounds scans all n. When k equals n it is O(n²). Space: O(n) for the used flags, plus O(k) for the lines.

    Edge cases and common mistakes

    • No used flags. Every round finds the same brand. Without the flags, the first two ranks would both be MegaCorp.
    • Ties. Using >= instead of > lets a later brand replace an earlier one with the same rating, so rank 1 would be NeoByte instead of MegaCorp. When all ratings are equal, strict comparison gives the brands in listing order: X, Y, Z with ratings 3, 3, 3 print as 1. X (3), 2. Y (3), 3. Z (3).
    • k equal to the number of brands. With k = 5 every brand is listed, ending with 4. Zenith (4) and 5. Quantum (3).
    • k larger than the number of brands. The task rules this out. With k = 6 on five brands, the sixth round finds nobody, bestIndex stays -1, and used[-1] throws ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5.
    • Resetting bestIndex outside the outer loop. The next round would start from the previous winner's index instead of -1.
    • Forgetting to mark the winner. If used[bestIndex] = true goes missing, the output repeats the first brand.

    Testing

    dataoutput
    the lesson's five brands, k = 31. MegaCorp (5), 2. NeoByte (5), 3. TechPro (4)
    the same, k = 11. MegaCorp (5)
    the same, k = 5MegaCorp, NeoByte, TechPro, Zenith, Quantum in that order, ratings 5, 5, 4, 4, 3
    X, Y, Z with ratings 3, 3, 3, k = 31. X (3), 2. Y (3), 3. Z (3)
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free