Start learning free

LESSON 254 OF 291 · NESTED LOOPS

Top K Brands V4 in Scala: Repeated 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 = Array("TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith")
        val ratings = Array(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 = Array.fill(ratings.size)(false) and val lines = scala.collection.mutable.ArrayBuffer[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 = Array("TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith")
        val ratings = Array(4, 5, 3, 5, 4)
        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 || ratings(i) > ratings(bestIndex)) {
                        bestIndex = i
                    }
                }
            }
            used(bestIndex) = true
            lines.append(s"$rank. ${brands(bestIndex)} (${ratings(bestIndex)})")
        }
        println(lines.mkString("\n"))

STEP 1 OF 11
    Ctrl + Enter to check

    SCALA · NESTED LOOPS

    Top K Brands V4 in Scala, explained

    Problem overview

    The starter code has two parallel arrays, brands and ratings, and a number k. Brand i has rating i. With five brands (TechPro 4, MegaCorp 5, Quantum 3, NeoByte 5 and Zenith 4) and k = 3, the program prints the three best brands in rank order, each line as rank. Brand (rating):

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

    MegaCorp and NeoByte are tied at 5, and the one listed first, MegaCorp, ranks first. TechPro and Zenith tie at 4, and TechPro takes the last place for the same reason. The value of k is never larger than the number of brands.

    Approach

    Finding one best brand is a scan: keep the index of the best so far, and replace it only for a strictly higher rating. Finding the top k means doing that k times, and each round has to ignore the brands that already won. A Boolean flag per brand records that.

    The replacement rule gives the tie-break for free. A later brand with an equal rating doesn't beat the current best, so the earlier one stays.

    The cost is k scans of n brands, O(k * n) in total. Sorting the brands by rating would cost O(n log n), but then the ties would need extra care to stay in listed order. The repeated scan keeps the rule visible in the code.

    Step by step

    1. Create used. Array.fill(ratings.size)(false) builds an array with one false for each brand. Nobody is taken at the start.
    2. Create lines. An empty ArrayBuffer[String] collects one finished line per rank. An ArrayBuffer can grow, which a plain Array can't.
    3. Loop over the ranks. for (rank <- 1 to k) includes k, and it gives the number to print in front of each brand.
    4. Reset bestIndex to -1 at the start of every round. The value -1 means nothing found yet.
    5. Nest a loop over every position of ratings. Each round looks at all the brands again.
    6. Skip taken brands: an if (!used(i)) lets only the available ones through.
    7. Compare. Inside it, an if checks that nothing is found yet or that this rating is strictly higher than the best one's.
    8. Remember the brand by setting bestIndex to i.
    9. Mark the winner after the inner loop: used(bestIndex) = true.
    10. Append the line: the rank, a dot and a space, the brand's name, and the rating in parentheses.
    11. Print the lines joined with newlines, after the loop.

    The solution in Scala

    val brands = Array("TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith")
    val ratings = Array(4, 5, 3, 5, 4)
    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 || ratings(i) > ratings(bestIndex)) {
                    bestIndex = i
                }
            }
        }
        used(bestIndex) = true
        lines.append(s"$rank. ${brands(bestIndex)} (${ratings(bestIndex)})")
    }
    println(lines.mkString("\n"))
    

    The three rounds

    In round 1 nothing is taken. The scan starts with TechPro (4), then MegaCorp (5) beats it, then Quantum (3) and NeoByte (5) don't beat 5, and Zenith (4) doesn't either. MegaCorp wins and its flag becomes true. In round 2 the scan skips MegaCorp, so NeoByte (5) is the highest of what remains. In round 3 both fives are taken, and among TechPro (4), Quantum (3) and Zenith (4) the first 4 stays: TechPro. Each round produces one line, in rank order, without any sorting.

    Details that matter in Scala

    The s string uses $rank for a simple name and ${brands(bestIndex)} for an expression. Braces are required whenever the placeholder is more than a plain name, such as a call or an index.

    1 to k is an inclusive range, while 0 until n stops before n. For k = 3, (1 to 3) is 1, 2, 3 and (1 until 3) is only 1, 2. Using until by mistake would print one line too few. ratings.indices is the range 0 until ratings.size.

    lines.mkString("\n") joins the entries with a newline between each two, and no newline after the last one. println adds that final newline.

    Edge cases and common mistakes

    • Ties. With three brands all rated 5, X, Y and Z, and k = 3, the output is 1. X (5), 2. Y (5), 3. Z (5): the listed order survives.
    • k = 1 and k equal to the number of brands. With k = 1 only 1. MegaCorp (5) prints. With k = 5 all five print, ending with 4. Zenith (4) and 5. Quantum (3).
    • k larger than the number of brands. The statement rules this out. If it happened, a round would find no brand, bestIndex would stay -1 and used(-1) would throw an ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5 for k = 6.
    • k = 0. The loop doesn't run, lines is empty, and println prints one blank line.
    • Forgetting to mark used. Every round would pick the same brand.
    • Using >=. A tie would then replace the earlier brand, and NeoByte would rank above MegaCorp.

    Complexity

    The two nested loops run k times n iterations, so the time is O(k * n). The extra space is the used array and the lines buffer, both O(n) at most.

    Key takeaways

    • The top k are k rounds of "find the best among the not-taken".
    • Replace the best only on a strictly higher value, so ties keep the earlier item.
    • 1 to k includes k; mkString("\n") puts one item on each line.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free