Start learning free

LESSON 255 OF 292 · NESTED LOOPS

Top K Brands V4 in Swift: Top K by Repeated Search

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:

        let brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
        let ratings = [4, 5, 3, 5, 4]
        let 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 print(...).

Start with the two declarations var used = Array(repeating: false, count: ratings.count) and var lines = [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.

        let brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
        let ratings = [4, 5, 3, 5, 4]
        let k = 3

        var used = Array(repeating: false, count: ratings.count)
        var lines = [String]()
        for rank in 1...k {
            var bestIndex = -1
            for index in ratings.indices {
                if !used[index] {
                    if bestIndex == -1 || ratings[index] > ratings[bestIndex] {
                        bestIndex = index
                    }
                }
            }
            used[bestIndex] = true
            lines.append("\(rank). \(brands[bestIndex]) (\(ratings[bestIndex]))")
        }
        print(lines.joined(separator: "\n"))

STEP 1 OF 11
    Ctrl + Enter to check

    SWIFT · NESTED LOOPS

    Top K Brands V4 in Swift, explained

    Problem overview

    Two parallel arrays describe five brands: brands holds the names and ratings holds their ratings, so position i in both refers to the same brand. A variable k says how many brands to show. The program prints the top k brands, best first, one per line, in the form rank. Brand (rating), starting at rank 1.

    When two brands have the same rating, the one listed first ranks higher. For the starter data, where k = 3, MegaCorp and NeoByte both have a 5 and MegaCorp is listed first, so the output is:

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

    In this version k is never larger than the number of brands.

    Approach: find the best, mark it taken, search again

    The previous version found the single best brand with one scan. To get the top k, the lesson repeats that scan k times. The only new problem is that every round after the first would find the same brand again, unless the earlier winners are ignored.

    A Bool array named used solves it. It has one flag per brand, all false at the start. A round looks only at brands whose flag is still false, picks the best of them, and sets that brand's flag to true. The next round then skips it, so the second-best brand can win, and so on.

    Inside a round the scan keeps a bestIndex that starts at -1, meaning "none found yet". A brand replaces the current best only if nothing is chosen yet or its rating is strictly higher. Strictly higher is what lets the earlier brand keep a tie.

    The cost is k scans of n brands, so the work grows with k * n. That is fine for small lists, and it needs no sorting.

    The rounds on the starter data

    Round (rank)bestIndexWinnerused after the round
    11MegaCorp (5)[false, true, false, false, false]
    23NeoByte (5)[false, true, false, true, false]
    30TechPro (4)[true, true, false, true, false]

    In round 1, MegaCorp at index 1 reaches a 5 first, and NeoByte's 5 at index 3 is not strictly higher, so MegaCorp keeps the spot. In round 2 MegaCorp is skipped, so NeoByte wins. In round 3 the two 5s are gone, and TechPro at index 0 reaches a 4 before Zenith, which ties it and doesn't replace it.

    Step by step

    1. Create used with Array(repeating: false, count: ratings.count), a var because the flags change.
    2. Create lines as an empty [String]. Each round adds one finished line to it.
    3. Loop over the ranks with for rank in 1...k. The counter does two jobs: it repeats the search once per winner and it is the number printed before the brand.
    4. Start the round with var bestIndex = -1. It is declared inside the loop, so every round restarts the search.
    5. Loop over the positions of ratings with for index in ratings.indices. Each round scans all brands from the start.
    6. Skip the taken brands with if !used[index].
    7. Test the candidate. Inside, check bestIndex == -1 || ratings[index] > ratings[bestIndex].
    8. Remember it by setting bestIndex = index.
    9. After the scan, mark the winner with used[bestIndex] = true.
    10. Add the line to lines with append, using string interpolation for the rank, the name and the rating.
    11. Print once at the end with lines.joined(separator: "\n").

    The solution in Swift

    let brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
    let ratings = [4, 5, 3, 5, 4]
    let k = 3
    
    var used = Array(repeating: false, count: ratings.count)
    var lines = [String]()
    for rank in 1...k {
        var bestIndex = -1
        for index in ratings.indices {
            if !used[index] {
                if bestIndex == -1 || ratings[index] > ratings[bestIndex] {
                    bestIndex = index
                }
            }
        }
        used[bestIndex] = true
        lines.append("\(rank). \(brands[bestIndex]) (\(ratings[bestIndex]))")
    }
    print(lines.joined(separator: "\n"))
    

    Swift specifics worth knowing:

    • 1...k is a closed range. It includes k, so k = 3 gives ranks 1, 2 and 3. The half-open 1..<k would stop one short. If k were 0, 1...0 is invalid and the program crashes at run time.
    • ratings.indices is the range of valid positions, 0..<5 here.
    • Interpolation handles numbers. "\(rank). \(brands[bestIndex]) (\(ratings[bestIndex]))" puts an Int and a String in one line. No String(...) conversion is needed, unlike with +.
    • joined(separator:) glues the strings of an array with the separator between each pair, and none after the last. One print then shows every line, and print adds the final newline.
    • Bounds are checked. used[-1] would stop the program, so the code relies on every round finding a brand. That holds because k never exceeds the number of brands.

    Edge cases and common mistakes

    • Ties. With ratings = [2, 2, 2] and k = 3, the brands come out in their listed order. Using >= instead of > would make the last tied brand win each round.
    • k = 1. The loop runs once and the output is only the best brand: 1. MegaCorp (5).
    • k equal to the number of brands. With k = 5 every brand is printed, in order: MegaCorp (5), NeoByte (5), TechPro (4), Zenith (4), Quantum (3).
    • Not marking the winner. Without used[bestIndex] = true, every round returns MegaCorp.
    • Declaring bestIndex outside the loop. The old winner would stay as the starting best, and a taken brand could appear again.
    • k larger than the number of brands. This lesson promises it doesn't happen. If it did, the last rounds would leave bestIndex at -1 and used[bestIndex] would crash.

    Testing

    These outputs come from running the solution on the starter arrays with other values of k.

    • k = 1 prints 1. MegaCorp (5).
    • k = 2 prints 1. MegaCorp (5) and 2. NeoByte (5).
    • k = 5 prints the five lines listed above, ending with 5. Quantum (3).

    Try it in the editor above, and set two ratings equal to check the tie rule.

    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free