Start learning free

LESSON 256 OF 291 · NESTED LOOPS

Top K Brands V6 in Kotlin: Breaking Rating Ties with 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:

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

Start from v4: the same val used = BooleanArray(ratings.size) and val lines = mutableListOf<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.

        val brands = arrayOf("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith")
        val ratings = intArrayOf(4, 5, 5, 3, 4)
        val reviews = intArrayOf(200, 150, 500, 100, 300)
        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) {
                        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.add("$rank. ${brands[bestIndex]} (${ratings[bestIndex]}, ${reviews[bestIndex]})")
        }
        println(lines.joinToString("\n"))

STEP 1 OF 12
    Ctrl + Enter to check

    KOTLIN · NESTED LOOPS

    Top K Brands V6 in Kotlin, explained

    Problem overview

    Three parallel arrays describe the brands: ratings[i] and reviews[i] belong to brands[i]. The program prints the top k brands as rank. Brand (rating, reviews). The rating decides first. When two brands have the same rating, the one with more reviews wins. If both are equal, the brand listed first wins. This version builds on the repeated search of version 4, with no filtering; only the comparison gets a second criterion.

    The starter code:

    indexbrandratingreviews
    0TechPro4200
    1MegaCorp5150
    2NeoByte5500
    3Quantum3100
    4Zenith4300

    With k = 3 the output is:

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

    NeoByte and MegaCorp share the top rating, and NeoByte has more reviews, so it comes first. Zenith and TechPro share rating 4, and Zenith has more reviews.

    Approach

    The search is the same as before. Each round scans all brands, skips the ones already taken (flagged in a used array), and keeps the position of the best in bestIndex. The winner is flagged and a line is added.

    The only change is the test that decides whether brand i beats the current best. It becomes a chain of three cases, checked in order:

    1. Nothing is found yet (bestIndex == -1): this brand is the best so far.
    2. This rating is higher than the best one's: it becomes the best, and reviews don't matter.
    3. The ratings are equal and this brand has more reviews: it becomes the best.

    Because the chain uses else if, a case runs only when the ones above it were false. When the ratings and the reviews are both equal, no case matches, the current best stays, and the brand listed first wins.

    On the lesson's data, round 1 ends with index 2 (NeoByte: rating 5, 500 reviews beats MegaCorp's 150). Round 2 picks index 1 (MegaCorp), the only brand left with rating 5. Round 3 picks index 4 (Zenith) over index 0 (TechPro), because both have rating 4 and 300 reviews is more than 200.

    Step by step

    1. Create used with one slot per rating, all false.
    2. Create lines, an empty mutableListOf<String>().
    3. Loop over the ranks with for (rank in 1..k). The counter is also the number printed before each brand.
    4. Reset bestIndex to -1 in every round.
    5. Write the inner loop over the positions of ratings.
    6. Skip taken brands with if (!used[i]).
    7. First case: when bestIndex is -1, set it to i.
    8. Second case, with else if: the rating is higher than the best one's.
    9. Third case, with another else if: the ratings are equal and the reviews are higher. Both conditions must hold.
    10. Mark the winner after the inner loop: used[bestIndex] = true.
    11. Add the line: 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 the lines joined with newlines.

    The solution in Kotlin

            val brands = arrayOf("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith")
            val ratings = intArrayOf(4, 5, 5, 3, 4)
            val reviews = intArrayOf(200, 150, 500, 100, 300)
            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) {
                            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.add("$rank. ${brands[bestIndex]} (${ratings[bestIndex]}, ${reviews[bestIndex]})")
            }
            println(lines.joinToString("\n"))
    

    Kotlin details worth a look:

    • else on a new line. The else if keywords sit on their own lines after the closing brace. Kotlin accepts that inside a statement chain; the lesson's formatting is only a style choice.
    • && needs both sides. The third case is true only when the ratings match and the reviews are higher. A lower rating with many reviews never reaches it, because the second case or the final fall-through has already decided.
    • Templates with expressions. In the line, $rank needs no braces, while ${brands[bestIndex]} and the other array reads do. The comma and the space between the two numbers are plain text in the string.
    • Three arrays, one index. bestIndex is enough to look up the name, the rating and the reviews, because all three arrays line up.

    Complexity

    Time: O(k * n) for n brands, since each of the k rounds scans all n and each comparison costs a constant amount. The extra criterion doesn't change the order of growth. Space: O(n) for used, plus O(k) for the lines.

    Edge cases and common mistakes

    • Ranking by reviews alone. Comparing only reviews would give NeoByte first here, which happens to be right, but a brand with rating 3 and 9,000 reviews would beat one with rating 5 and 10. With names Loud (3, 9000) and Good (5, 10), the output is 1. Good (5, 10) then 2. Loud (3, 9000), because the rating decides first.
    • Forgetting the equal-rating condition. In the third case, reviews[i] > reviews[bestIndex] alone, without ratings[i] == ratings[bestIndex], would let a lower-rated brand with many reviews replace a better one.
    • A tie on rating where the later brand has more reviews. A (5, 10) and B (5, 20) print as 1. B (5, 20) and 2. A (5, 10).
    • A tie on everything. A, B and C, each rated 4 with 10 reviews, print in listing order: A, B, C. That needs strict > in both comparisons. With >= on the reviews, a later brand would replace an earlier one that is equal in both.
    • Missing used flags. Every round would pick NeoByte again.
    • k larger than the number of brands. The task rules it out. Then a round finds nobody and used[-1] throws. With k = 5 every brand is listed: NeoByte, MegaCorp, Zenith, TechPro, Quantum.
    • Resetting bestIndex too early or too late. It belongs at the start of each round, inside the outer loop.

    Testing

    dataoutput
    the lesson's five brands, k = 31. NeoByte (5, 500), 2. MegaCorp (5, 150), 3. Zenith (4, 300)
    the same, k = 11. NeoByte (5, 500)
    the same, k = 5NeoByte, MegaCorp, Zenith (4, 300), TechPro (4, 200), Quantum (3, 100)
    Loud (3, 9000) and Good (5, 10), k = 21. Good (5, 10), 2. Loud (3, 9000)
    A (5, 10) and B (5, 20), k = 21. B (5, 20), 2. A (5, 10)
    A, B, C all (4, 10), k = 31. A (4, 10), 2. B (4, 10), 3. C (4, 10)
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free