Start learning free

LESSON 256 OF 291 · NESTED LOOPS

Top K Brands V6 in Scala: Ranking with a Tie-Break on 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 = Array("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith")
        val ratings = Array(4, 5, 5, 3, 4)
        val reviews = Array(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 = Array.fill(ratings.size)(false) and val lines = scala.collection.mutable.ArrayBuffer[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 = Array("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith")
        val ratings = Array(4, 5, 5, 3, 4)
        val reviews = Array(200, 150, 500, 100, 300)
        val k = 3

        val used = Array.fill(ratings.size)(false)
        val lines = scala.collection.mutable.ArrayBuffer[String]()
        for (rank <- 1 to k) {
            var bestIndex = -1
            for (i <- 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.append(s"$rank. ${brands(bestIndex)} (${ratings(bestIndex)}, ${reviews(bestIndex)})")
        }
        println(lines.mkString("\n"))

STEP 1 OF 12
    Ctrl + Enter to check

    SCALA · NESTED LOOPS

    Top K Brands V6 in Scala, explained

    Problem overview

    The starter code has three parallel arrays, brands, ratings and reviews, and a number k, here 3. The program ranks the top k brands. Rating decides first: the higher rating wins. When two brands have the same rating, the one with more reviews wins. If both are equal, the one listed first wins. Each line has the form rank. Brand (rating, reviews). The value of k is never larger than the number of brands.

    For the starter data the output is:

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

    NeoByte and MegaCorp both have a 5, and NeoByte has more reviews. Zenith and TechPro both have a 4, and Zenith's 300 reviews beat TechPro's 200.

    Approach

    The method is the repeated search used for plain top-k: k rounds, each scanning the brands that aren't taken, keeping the index of the best, and marking the winner. The only change is the test that decides whether a candidate replaces the current best. It now has three cases, checked in order:

    1. Nothing is chosen yet, so the candidate is the best so far.
    2. The candidate's rating is higher, so it wins, whatever the reviews are.
    3. The ratings are equal and the candidate has more reviews, so it wins.

    Every other candidate leaves the best unchanged. That includes a candidate that ties on both values, and that is exactly how a tie on rating and reviews goes to the brand listed first: the later brand doesn't replace the earlier one.

    The order of the cases is what makes the rating more important than the reviews. A brand with a low rating and many reviews never gets to the review comparison, because its rating is neither higher nor equal. For two brands, Low (rating 3, 9000 reviews) and High (rating 5, 1 review), the ranking is High first, then Low.

    Step by step

    1. Create used with Array.fill(ratings.size)(false), one flag per brand.
    2. Create lines, an empty ArrayBuffer[String].
    3. Loop over the ranks with for (rank <- 1 to k).
    4. Set bestIndex to -1 at the start of each round.
    5. Nest a loop over the positions of ratings.
    6. Skip the taken brands with if (!used(i)).
    7. First case: if 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.
    10. Mark the winner after the inner loop: used(bestIndex) = true.
    11. Append the line with the rank, the name, then the rating and the review count in parentheses, separated by a comma and a space.
    12. Print the lines joined by newlines.

    The solution in Scala

    val brands = Array("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith")
    val ratings = Array(4, 5, 5, 3, 4)
    val reviews = Array(200, 150, 500, 100, 300)
    val k = 3
    
    val used = Array.fill(ratings.size)(false)
    val lines = scala.collection.mutable.ArrayBuffer[String]()
    for (rank <- 1 to k) {
        var bestIndex = -1
        for (i <- 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.append(s"$rank. ${brands(bestIndex)} (${ratings(bestIndex)}, ${reviews(bestIndex)})")
    }
    println(lines.mkString("\n"))
    

    Details that matter in Scala

    The three cases are an if / else if chain, so only the first true one runs. The first case has to come first: when bestIndex is -1, the later cases would call ratings(bestIndex) and fail with an index error. Because of the chain, they are never evaluated in that situation.

    The condition ratings(i) == ratings(bestIndex) && reviews(i) > reviews(bestIndex) needs both parts. In Scala, == on Int compares values, as you would hope. The third case does not repeat the check for a higher rating, since the second case has already taken that one.

    The string s"$rank. ${brands(bestIndex)} (${ratings(bestIndex)}, ${reviews(bestIndex)})" uses braces around every placeholder that is an index expression. $rank is a plain name, so it needs none. The dot after it ends the name, so it isn't swallowed by the placeholder.

    Edge cases and common mistakes

    • More reviews, same rating. For A, B and C with ratings 4, 4, 4 and reviews 10, 30, 20, the order is B (30), C (20), A (10).
    • A complete tie. With P, Q and R all at 4 and 10 reviews, the output keeps the listed order: P, Q, R. Two brands with equal values are never swapped.
    • Using >= for reviews. This would let a later brand with equal reviews replace the earlier one and break the rule that the earlier brand wins.
    • Comparing reviews first. A brand with 9000 reviews and a 3 would then outrank a 5. The rating has to come first.
    • k equal to the number of brands. With k = 5, the starter data ranks NeoByte (5, 500), MegaCorp (5, 150), Zenith (4, 300), TechPro (4, 200) and Quantum (3, 100). With k = 1 only NeoByte prints.
    • Combining the criteria in one number. Adding rating and reviews would be wrong, as the two values aren't comparable.

    Complexity

    Each of the k rounds scans all n brands in constant time per brand, so the time is O(k * n). The extra space is the used array and the lines buffer.

    Key takeaways

    • A tie-break is a second condition checked only when the first one is equal.
    • An else if chain evaluates the cases in order, so put the main criterion before the secondary one.
    • Keeping the earlier item on a full tie needs strict comparisons.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free