Start learning free

LESSON 255 OF 291 · NESTED LOOPS

Top K Brands V5 in Kotlin: 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 = arrayOf("Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop")
        val brands = arrayOf("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech")
        val ratings = intArrayOf(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 = arrayOf("Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop")
        val brands = arrayOf("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech")
        val ratings = intArrayOf(4, 5, 5, 3, 4, 4)
        val target = "Laptop"
        val k = 2

        val filteredBrands = mutableListOf<String>()
        val filteredRatings = mutableListOf<Int>()
        for (i in 0 until products.size) {
            if (products[i] == target) {
                filteredBrands.add(brands[i])
                filteredRatings.add(ratings[i])
            }
        }
        val used = BooleanArray(filteredRatings.size)
        val lines = mutableListOf<String>()
        for (rank in 1..k) {
            var bestIndex = -1
            for (i in 0 until filteredRatings.size) {
                if (!used[i]) {
                    if (bestIndex == -1 || filteredRatings[i] > filteredRatings[bestIndex]) {
                        bestIndex = i
                    }
                }
            }
            if (bestIndex != -1) {
                used[bestIndex] = true
                lines.add(rank.toString() + ". " + filteredBrands[bestIndex] + " (" + filteredRatings[bestIndex] + ")")
            }
        }
        println(lines.joinToString("\n"))

STEP 1 OF 18
    Ctrl + Enter to check

    KOTLIN · NESTED LOOPS

    Top K Brands V5 in Kotlin, explained

    Problem overview

    The catalog now lists many products. Row i of three parallel structures describes one entry: products[i] is the product, brands[i] the brand that sells it and ratings[i] its rating. The program keeps only the rows whose product equals target, then prints the top k of them by rating as rank. Brand (rating). Ties go to the entry listed first.

    The starter code:

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

    Three rows sell a Laptop: TechPro (4), NeoByte (5) and AlphaTech (4). The two best are NeoByte and then TechPro, which is listed before AlphaTech:

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

    If fewer than k rows match, the program lists only the ones that exist, with no extra lines and no error.

    Approach

    The work splits into two parts. First, filter: copy the brand and the rating of every matching row into two new lists, in the same order, so the position in one list still matches the position in the other. Second, run the previous version's repeated search on those filtered lists: each round picks the best brand not taken yet, marks it in a used array, and adds a line.

    The filtered lists must be real lists that grow, because nobody knows in advance how many rows match. That is why they are mutableListOf lists and not arrays. The search then uses their sizes, not the sizes of the original arrays. For the lesson's data the filtered lists are [TechPro, NeoByte, AlphaTech] and [4, 5, 4].

    There is one new situation compared with the previous version. When fewer than k brands match, a round can find nobody, so bestIndex is still -1 after the inner loop. The program must check for that before using it.

    Step by step

    1. Create filteredBrands, an empty mutableListOf<String>().
    2. Create filteredRatings, an empty mutableListOf<Int>().
    3. Loop over every row. i takes each position of products, and the three arrays line up at that position.
    4. Test the product. An if checks products[i] == target, so other rows are skipped.
    5. Copy the brand into filteredBrands with add.
    6. Copy the rating into filteredRatings the same way, so both lists keep the same order.
    7. Create used after the loop, sized to the filtered ratings, not to the original arrays.
    8. Create lines, an empty list of strings for the finished lines.
    9. Loop over the ranks with for (rank in 1..k).
    10. Reset bestIndex to -1 in every round.
    11. Write the inner loop over the positions of filteredRatings.
    12. Skip taken entries by testing !used[i].
    13. Compare. An entry becomes the best when nothing is found yet or its rating is strictly higher.
    14. Remember it by setting bestIndex = i.
    15. Guard against an empty round. After the inner loop, continue only when bestIndex != -1.
    16. Mark the winner with used[bestIndex] = true.
    17. Add the line to lines: the rank, a dot and a space, the brand, and the rating in parentheses.
    18. Print the lines joined with newlines.

    The solution in Kotlin

            val products = arrayOf("Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop")
            val brands = arrayOf("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech")
            val ratings = intArrayOf(4, 5, 5, 3, 4, 4)
            val target = "Laptop"
            val k = 2
    
            val filteredBrands = mutableListOf<String>()
            val filteredRatings = mutableListOf<Int>()
            for (i in 0 until products.size) {
                if (products[i] == target) {
                    filteredBrands.add(brands[i])
                    filteredRatings.add(ratings[i])
                }
            }
            val used = BooleanArray(filteredRatings.size)
            val lines = mutableListOf<String>()
            for (rank in 1..k) {
                var bestIndex = -1
                for (i in 0 until filteredRatings.size) {
                    if (!used[i]) {
                        if (bestIndex == -1 || filteredRatings[i] > filteredRatings[bestIndex]) {
                            bestIndex = i
                        }
                    }
                }
                if (bestIndex != -1) {
                    used[bestIndex] = true
                    lines.add(rank.toString() + ". " + filteredBrands[bestIndex] + " (" + filteredRatings[bestIndex] + ")")
                }
            }
            println(lines.joinToString("\n"))
    

    Kotlin details worth a look:

    • == compares contents. products[i] == target calls equals on the strings, so it is true for two different String objects holding the same text. It is case sensitive: a target of "laptop" matches nothing here.
    • Two inner loops, two index names. Both loops call their variable i. That is fine, because the first loop has finished before the second starts, and each i exists only inside its own loop.
    • size on lists and arrays. Arrays and lists both have a size property. The search loop uses filteredRatings.size, the number of matches, not ratings.size.
    • Building the line with +. rank is an Int, so rank.toString() comes first to start a String. After that, + converts each number it meets on the right-hand side.
    • List<Int> boxes its numbers. A MutableList<Int> holds boxed integers, unlike IntArray. For this lesson's sizes that makes no difference.

    Complexity

    Time: O(n + k * m), where n is the number of rows and m the number of matches. The filter scans the n rows once, and then each of the k rounds scans the m filtered entries. Space: O(m) for the filtered lists and the used flags, plus O(k) for the lines.

    Edge cases and common mistakes

    • Fewer matches than k. With target = "Tablet" and k = 3, only 1. Quantum (3) prints. With "Laptop" and k = 5 the three Laptop lines print and rounds 4 and 5 add nothing.
    • No match at all. With target = "Desktop" every round finds nobody, lines stays empty, and println prints an empty line. There is no error.
    • Missing the guard. Without bestIndex != -1, the first round with nobody left throws ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 1 on a one-element list.
    • Sizing used from the original arrays. It would have six slots for three entries. The extra slots stay false and are never read, so the code may still seem to work, but the array doesn't match the lists it describes. Size it from the filtered lists.
    • Case and spelling. "laptop" is not "Laptop", so the filter keeps nothing.
    • Ties. TechPro and AlphaTech both have 4, and the one listed first comes first. The strict > in the comparison is what keeps that order.
    • Filtering one list only. If a rating is copied without its brand, the lists drift apart and the names no longer match the ratings. Both add calls belong to the same if.

    Testing

    target, koutput
    Laptop, 21. NeoByte (5), 2. TechPro (4)
    Phone, 21. MegaCorp (5), 2. Zenith (4)
    Laptop, 31. NeoByte (5), 2. TechPro (4), 3. AlphaTech (4)
    Laptop, 5the same three lines
    Tablet, 31. Quantum (3)
    Desktop, 2an empty line
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free