Start learning free

LESSON 255 OF 291 · NESTED LOOPS

Top K Brands V5 in Scala: Filter by Product, Then Rank the Top K

Practice Read the full explanation

The full catalog covers many products. Filter to one product first, then rank the top k brands that sell it, using v4's repeated search on the filtered lists.

You start with:

        val products = Array("Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop")
        val brands = Array("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech")
        val ratings = Array(4, 5, 5, 3, 4, 4)
        val target = "Laptop"
        val k = 2

Build:

1. NeoByte (5)
2. TechPro (4)

Rules:

  • Filter: copy the brand and the rating of every row whose product equals target into two new lists, keeping the order.
  • From the filtered lists pick the top k by rating, highest first, with v4's repeated search. Ties go to the entry listed first.
  • If fewer than k products match, list only those that exist: when no brand is left, add no more lines (no extra lines, no error).
  • Each line is "rank. Brand (rating)", starting at rank 1.
  • Print the lines, one per line, with println(...).

Build filteredBrands and filteredRatings first: a loop over the catalog that copies the row when products(i) == target.

Then run v4's repeated search over the filtered lists (same code, new names).

If fewer than k products match, some round finds nobody (bestIndex stays -1): add a line only when a brand was found.

        val products = Array("Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop")
        val brands = Array("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech")
        val ratings = Array(4, 5, 5, 3, 4, 4)
        val target = "Laptop"
        val k = 2

        val filteredBrands = scala.collection.mutable.ArrayBuffer[String]()
        val filteredRatings = scala.collection.mutable.ArrayBuffer[Int]()
        for (i <- 0 until products.size) {
            if (products(i) == target) {
                filteredBrands.append(brands(i))
                filteredRatings.append(ratings(i))
            }
        }
        val used = Array.fill(filteredRatings.size)(false)
        val lines = scala.collection.mutable.ArrayBuffer[String]()
        for (rank <- 1 to k) {
            var bestIndex = -1
            for (i <- 0 until filteredRatings.size) {
                if (!used(i)) {
                    if (bestIndex == -1 || filteredRatings(i) > filteredRatings(bestIndex)) {
                        bestIndex = i
                    }
                }
            }
            if (bestIndex != -1) {
                used(bestIndex) = true
                lines.append(rank.toString() + ". " + filteredBrands(bestIndex) + " (" + filteredRatings(bestIndex) + ")")
            }
        }
        println(lines.mkString("\n"))

STEP 1 OF 18
    Ctrl + Enter to check

    SCALA · NESTED LOOPS

    Top K Brands V5 in Scala, explained

    Problem overview

    The catalog now covers several products. The starter code has three parallel arrays, products, brands and ratings, where row i says that brand i sells product i with rating i. It also has a target product, here "Laptop", and a number k, here 2.

    The program first keeps only the rows whose product equals target. Then it ranks the top k of them by rating, highest first, and prints each as rank. Brand (rating). Ties go to the entry listed first. If fewer than k rows match, only the existing ones are printed. For the starter data the three laptop brands are TechPro (4), NeoByte (5) and AlphaTech (4), so the output is:

    1. NeoByte (5)
    2. TechPro (4)
    

    Approach

    There are two phases. The first is a filter: one pass over the catalog copies the brand and the rating of every matching row into two new lists, keeping the original order. The second is the repeated search from the previous version, run on the filtered lists: k rounds, each finding the best brand not yet taken by a strict comparison, and marking it.

    Filtering first matters because the ranking should only see the target product. Brands that sell phones or tablets must not take a rank, however high their rating is: MegaCorp has a 5 for a phone, but it doesn't appear in the laptop ranking.

    The filtered lists need to grow as matches are found, and their final size isn't known in advance, so they are ArrayBuffer values instead of fixed-size arrays. Because the brand and its rating are appended together, they stay at the same position in both lists.

    Step by step

    1. Create filteredBrands, an empty ArrayBuffer[String].
    2. Create filteredRatings, an empty ArrayBuffer[Int], for the matching ratings.
    3. Loop over the catalog. for (i <- 0 until products.size) visits every row.
    4. Test the product. if (products(i) == target). In Scala == compares the text of two strings, not their identity.
    5. Append the brand to filteredBrands.
    6. Append the rating to filteredRatings, in the same order.
    7. Create used, sized by the filtered ratings: Array.fill(filteredRatings.size)(false). Its length is the number of matches, not the size of the catalog.
    8. Create lines, an empty ArrayBuffer[String], for the output.
    9. Loop over the ranks with for (rank <- 1 to k).
    10. Set bestIndex to -1 at the start of each round.
    11. Nest a loop over the positions of filteredRatings.
    12. Skip taken entries with if (!used(i)).
    13. Compare strictly: nothing found yet, or a higher rating than the best one's.
    14. Remember it: bestIndex = i.
    15. Check a brand was found with bestIndex != -1, because a round can run out of brands.
    16. Mark the winner as used.
    17. Append the line, built from the rank, the brand and the rating.
    18. Print the lines joined with newlines.

    The solution in Scala

    val products = Array("Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop")
    val brands = Array("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech")
    val ratings = Array(4, 5, 5, 3, 4, 4)
    val target = "Laptop"
    val k = 2
    
    val filteredBrands = scala.collection.mutable.ArrayBuffer[String]()
    val filteredRatings = scala.collection.mutable.ArrayBuffer[Int]()
    for (i <- 0 until products.size) {
        if (products(i) == target) {
            filteredBrands.append(brands(i))
            filteredRatings.append(ratings(i))
        }
    }
    val used = Array.fill(filteredRatings.size)(false)
    val lines = scala.collection.mutable.ArrayBuffer[String]()
    for (rank <- 1 to k) {
        var bestIndex = -1
        for (i <- 0 until filteredRatings.size) {
            if (!used(i)) {
                if (bestIndex == -1 || filteredRatings(i) > filteredRatings(bestIndex)) {
                    bestIndex = i
                }
            }
        }
        if (bestIndex != -1) {
            used(bestIndex) = true
            lines.append(rank.toString() + ". " + filteredBrands(bestIndex) + " (" + filteredRatings(bestIndex) + ")")
        }
    }
    println(lines.mkString("\n"))
    

    Details that matter in Scala

    Inside the loops, filteredRatings(i) reads an ArrayBuffer with parentheses, just as it does with an array, and append adds an element at the end. The line is built with rank.toString() + ". " + filteredBrands(bestIndex) + " (" + filteredRatings(bestIndex) + ")". rank.toString() turns the Int into text, and the + operator joins it with the other pieces; the numeric rating is converted to text the same way when it follows a string.

    The positions in used and bestIndex refer to the filtered lists, not to the catalog. The brand at filtered position 1 is NeoByte, even though it sits at position 2 in the original catalog. Mixing the two kinds of index is a classic source of wrong output.

    Edge cases and common mistakes

    • More k than matches. With k = 3 the laptop ranking has three lines: NeoByte (5), TechPro (4) and AlphaTech (4). With k = 5 it still has just these three, because the last two rounds find no brand and the bestIndex != -1 check keeps them silent.
    • One match. For "Tablet" and k = 2, only 1. Quantum (3) prints.
    • No match. For a product that isn't in the catalog, such as "Watch", the lines buffer stays empty and println prints one blank line.
    • Case matters. "laptop" in lowercase doesn't equal "Laptop", so it matches nothing and prints a blank line.
    • Phones. For "Phone" and k = 2 the output is 1. MegaCorp (5) and 2. Zenith (4).
    • Ties. TechPro and AlphaTech both have a 4 for laptops, and TechPro is listed first, so it ranks above AlphaTech.

    Complexity

    The filter pass is O(n) for n catalog rows. If m rows match, the search costs O(k * m). The two filtered buffers and the used array take O(m) space.

    Key takeaways

    • Filter first, then rank: the ranking sees only the rows that match.
    • Append related values to separate buffers in the same order to keep their positions aligned.
    • Guard each round with bestIndex != -1 when there may be fewer than k candidates.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free