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
- Create
used.Array.fill(ratings.size)(false)builds an array with onefalsefor each brand. Nobody is taken at the start. - Create
lines. An emptyArrayBuffer[String]collects one finished line per rank. AnArrayBuffercan grow, which a plainArraycan't. - Loop over the ranks.
for (rank <- 1 to k)includesk, and it gives the number to print in front of each brand. - Reset
bestIndexto -1 at the start of every round. The value -1 means nothing found yet. - Nest a loop over every position of
ratings. Each round looks at all the brands again. - Skip taken brands: an
if (!used(i))lets only the available ones through. - Compare. Inside it, an
ifchecks that nothing is found yet or that this rating is strictly higher than the best one's. - Remember the brand by setting
bestIndextoi. - Mark the winner after the inner loop:
used(bestIndex) = true. - Append the line: the rank, a dot and a space, the brand's name, and the rating in parentheses.
- 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 is1. X (5),2. Y (5),3. Z (5): the listed order survives. k= 1 andkequal to the number of brands. Withk= 1 only1. MegaCorp (5)prints. Withk= 5 all five print, ending with4. Zenith (4)and5. Quantum (3).klarger than the number of brands. The statement rules this out. If it happened, a round would find no brand,bestIndexwould stay -1 andused(-1)would throw anArrayIndexOutOfBoundsException:Index -1 out of bounds for length 5fork= 6.k= 0. The loop doesn't run,linesis empty, andprintlnprints 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
karekrounds 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 kincludesk;mkString("\n")puts one item on each line.
