Start learning free

LESSON 195 OF 415 · NESTED LOOPS

Top K Brands V5 - Filter by Product in Swift

Practice

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

    Top K Brands V5 in Swift

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