Start learning free

LESSON 256 OF 292 · NESTED LOOPS

Top K Brands V5 in Swift: Filter by Product, Then Rank

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:

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

Build filteredBrands and filteredRatings first: a loop over the catalog that copies the row when products[index] == 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.

        let products = ["Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"]
        let brands = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"]
        let ratings = [4, 5, 5, 3, 4, 4]
        let target = "Laptop"
        let k = 2

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

STEP 1 OF 18
    Ctrl + Enter to check

    SWIFT · NESTED LOOPS

    Top K Brands V5 in Swift, explained

    Problem overview

    The catalog is now a list of rows spread over three parallel arrays: products, brands and ratings. Row i says that the brand brands[i] sells the product products[i] with the rating ratings[i]. A variable target names one product and k says how many brands to show.

    The program first keeps only the rows of the target product, then ranks the top k brands among them by rating, highest first. Ties go to the entry listed first. Each line has the form rank. Brand (rating), starting at rank 1. With target = "Laptop" and k = 2 the output is:

    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: two stages

    The work splits into two independent stages. The first is a filter: walk through every row and copy the brand and rating of each row whose product equals target into two new arrays, keeping the order. The second is the repeated search from the previous version, run on the filtered arrays instead of the full ones: find the best entry that isn't taken yet, mark it taken, and repeat k times.

    Because the filter keeps the order, the tie rule still works: among equal ratings, the entry that comes first in the catalog comes first in the filtered arrays. The filtered brand and rating arrays always have the same length, and a brand and its rating sit at the same position in both.

    The only new risk is in the second stage. The filtered lists can be shorter than k, so a round may find nothing. The round must check for that before using its result.

    The filter on the starter data

    The rows for "Laptop" are at positions 0, 2 and 5. After the filter, filteredBrands is ["TechPro", "NeoByte", "AlphaTech"] and filteredRatings is [4, 5, 4]. Round 1 picks NeoByte (5). Round 2 has TechPro and AlphaTech, both rated 4, and the one listed first, TechPro, wins.

    Step by step

    1. Create filteredBrands as an empty [String] and filteredRatings as an empty [Int].
    2. Loop over the rows with for index in products.indices.
    3. Keep the matching rows. If products[index] == target, append brands[index] to one array and ratings[index] to the other, in the same order.
    4. Create used with one false per filtered rating. It must be as long as the filtered lists, not the full catalog.
    5. Create lines as an empty [String].
    6. Loop over the ranks with for rank in 1...k, and start each round with var bestIndex = -1.
    7. Scan the filtered ratings. For each index that isn't used, take it if nothing is chosen yet or its rating is strictly higher than the best one's.
    8. Check that something was found with bestIndex != -1, because a round may have nobody left.
    9. Inside the check, set used[bestIndex] to true and append the formatted line to lines.
    10. Print the lines joined with "\n".

    The solution in Swift

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

    Swift specifics worth knowing:

    • == compares strings by content. products[index] == target is true when the two strings have the same characters. Case matters: "laptop" does not equal "Laptop".
    • Empty arrays with a type. [String]() and [Int]() create empty arrays whose element types are fixed, so append accepts only the right kind of value.
    • indices of the filtered array. The scan uses filteredRatings.indices, the positions of the filtered list. Using ratings.indices there would index the filtered arrays with positions that may not exist.
    • 1...k with a short list. The loop always runs k times. The bestIndex != -1 check is what keeps the rounds without a winner silent.
    • Printing an empty array's lines. If nothing matches, lines is empty, joined gives an empty string, and print outputs a single blank line.

    Edge cases and common mistakes

    • Fewer matches than k. With target = "Phone" and k = 3 only two rows match, so the output is 1. MegaCorp (5) and 2. Zenith (4), with no third line. With "Tablet" and k = 2 the output is only 1. Quantum (3).
    • No match at all. With target = "Watch", or "laptop" in lower case, the filtered lists are empty and the program prints just an empty line.
    • Ranking before filtering. If you rank the whole catalog first, brands of other products take places in the top k. The filter has to come first.
    • Sizing used from the full catalog. It would have extra flags that no filtered entry owns, which doesn't crash but is wrong in principle. Size it from the filtered arrays.
    • Skipping the bestIndex check. Without it, used[-1] crashes the program as soon as k exceeds the number of matches.
    • Ties. With target = "Laptop" and k = 3, TechPro and AlphaTech both have a 4, and the output keeps catalog order: NeoByte, TechPro, AlphaTech.

    Testing

    These outputs come from the solution on the starter catalog.

    targetkoutput
    "Laptop"31. NeoByte (5), 2. TechPro (4), 3. AlphaTech (4)
    "Laptop"5the same three lines
    "Phone"11. MegaCorp (5)
    "Phone"31. MegaCorp (5), 2. Zenith (4)
    "Watch"2a blank line

    Try these in the editor above by changing target and k.

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