Problem overview
Two parallel arrays hold the data: ratings[i] is the rating of brands[i]. The previous version found the single best brand. This version prints the top k brands in rank order, one line each, as rank. Brand (rating). Ties go to the brand listed first, and k is never larger than the number of brands.
The starter code has five brands and k = 3:
| index | brand | rating |
|---|---|---|
| 0 | TechPro | 4 |
| 1 | MegaCorp | 5 |
| 2 | Quantum | 3 |
| 3 | NeoByte | 5 |
| 4 | Zenith | 4 |
1. MegaCorp (5)
2. NeoByte (5)
3. TechPro (4)
Approach
Finding the best brand is a loop that keeps the position of the best one seen so far. To get the second best, run the same search again, but ignore the brand that already won. Do that k times and the winners come out in rank order. This is a nested loop: the outer one runs once per rank, and the inner one scans every brand.
To ignore winners, keep one true/false flag per brand in a BooleanArray named used. A brand whose flag is true is skipped by later rounds, so no brand wins twice.
On the lesson's data, rank 1 picks index 1 (MegaCorp, 5). Index 3 also has 5, but it isn't strictly higher, so the earlier brand stays. Rank 2 sees index 1 as used and picks index 3 (NeoByte). Rank 3 picks index 0 (TechPro, 4), the first of the two remaining brands with rating 4.
Step by step
- Create
usedwith one slot per rating. All slots start asfalse. - Create
lines, an emptymutableListOf<String>(). Each round adds one finished line to it. - Loop over the ranks.
for (rank in 1..k)makesranktake 1, 2, ...,k. The counter also serves as the number printed before each brand. - Reset
bestIndexto -1 at the start of every round. -1 is not a position, so it means "no brand found yet". - Write the inner loop over the positions of
ratings, so every round looks at every brand again. - Skip taken brands. Only an
if (!used[i])brand can become the round's best. - Compare. The brand becomes the best when nothing is found yet, or when its rating is strictly higher than the best one's. Strictly higher keeps the earlier brand on a tie.
- Remember the brand by setting
bestIndex = i. - Mark the winner after the inner loop with
used[bestIndex] = true. - Add the line to
lines: the rank, a dot and a space, the name and the rating in parentheses. - Print all the lines joined with a newline between them.
The solution in Kotlin
val brands = arrayOf("TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith")
val ratings = intArrayOf(4, 5, 3, 5, 4)
val k = 3
val used = BooleanArray(ratings.size)
val lines = mutableListOf<String>()
for (rank in 1..k) {
var bestIndex = -1
for (i in ratings.indices) {
if (!used[i]) {
if (bestIndex == -1 || ratings[i] > ratings[bestIndex]) {
bestIndex = i
}
}
}
used[bestIndex] = true
lines.add("$rank. ${brands[bestIndex]} (${ratings[bestIndex]})")
}
println(lines.joinToString("\n"))
Kotlin details worth a look:
- Two kinds of range.
1..kincludesk, so withk = 3it is 1, 2, 3.ratings.indicesis0..4for five ratings, the valid positions of the array, written without the bounds. - String templates. In
"$rank. ${brands[bestIndex]} (${ratings[bestIndex]})", a plain name after$is enough forrank, but an expression such as an array access needs braces. The dot right after$rankis ordinary text. MutableList.mutableListOf<String>()starts empty and grows withadd. A list made withlistOfcouldn't be added to.joinToString("\n"). It glues the items together with the separator between each two and none after the last, soprintlnends the output with a single line break. With an empty list it returns an empty string.varversusval.bestIndexchanges during the search, so it is avar. The arrays and the list areval: the variable never points to a different object, even though the contents change.
Complexity
Time: O(k * n) for n brands, since each of the k rounds scans all n. When k equals n it is O(n²). Space: O(n) for the used flags, plus O(k) for the lines.
Edge cases and common mistakes
- No
usedflags. Every round finds the same brand. Without the flags, the first two ranks would both be MegaCorp. - Ties. Using
>=instead of>lets a later brand replace an earlier one with the same rating, so rank 1 would be NeoByte instead of MegaCorp. When all ratings are equal, strict comparison gives the brands in listing order: X, Y, Z with ratings 3, 3, 3 print as1. X (3),2. Y (3),3. Z (3). kequal to the number of brands. Withk = 5every brand is listed, ending with4. Zenith (4)and5. Quantum (3).klarger than the number of brands. The task rules this out. Withk = 6on five brands, the sixth round finds nobody,bestIndexstays -1, andused[-1]throwsArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5.- Resetting
bestIndexoutside the outer loop. The next round would start from the previous winner's index instead of -1. - Forgetting to mark the winner. If
used[bestIndex] = truegoes missing, the output repeats the first brand.
Testing
| data | output |
|---|---|
the lesson's five brands, k = 3 | 1. MegaCorp (5), 2. NeoByte (5), 3. TechPro (4) |
the same, k = 1 | 1. MegaCorp (5) |
the same, k = 5 | MegaCorp, NeoByte, TechPro, Zenith, Quantum in that order, ratings 5, 5, 4, 4, 3 |
X, Y, Z with ratings 3, 3, 3, k = 3 | 1. X (3), 2. Y (3), 3. Z (3) |
