Start learning free

LESSON 187 OF 292 · LOOPING OVER ARRAY INDICES

Top K Brands V3 in Swift: Finding the Best Rating in an Array

Practice Read the full explanation

Many brands sell the same product, stored in two parallel arrays: ratings[i] is the rating of brands[i]. Find the highest-rated brand by scanning with a loop.

You start with:

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

Build:

1. MegaCorp (5)

Rules:

  • Keep the position of the best brand so far in bestIndex, starting at 0, and scan the positions from 1 to the end with a loop.
  • Update bestIndex only on a strictly higher rating. If two brands share the top rating, the one listed first wins (MegaCorp at position 1, not NeoByte at position 3).
  • Format the winner as "1. Brand (rating)" and print it with print(...).

Walk the positions with for index in 1..<ratings.count { and compare each rating with the best one so far.

Swift puts any value into a string with interpolation: "\(value)".

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

        var bestIndex = 0
        for index in 1..<ratings.count {
            if ratings[index] > ratings[bestIndex] {
                bestIndex = index
            }
        }
        print("1. \(brands[bestIndex]) (\(ratings[bestIndex]))")

STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · LOOPING OVER ARRAY INDICES

    Top K Brands V3 in Swift, explained

    Problem overview

    Many brands sell the same product. They are stored in two parallel arrays: ratings[i] is the rating of brands[i]. The program finds the highest-rated brand by scanning with a loop and prints it as 1. Brand (rating). If two brands share the top rating, the one listed first wins.

    For the starter data, ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"] with ratings [4, 5, 3, 5, 4], the top rating is 5. MegaCorp (position 1) and NeoByte (position 3) both have it, and MegaCorp is listed first:

    1. MegaCorp (5)
    

    Version 2 chose between two brands with an if/else. A loop does the same job for any number of brands.

    Approach: remember the position of the best so far

    Keep a variable, bestIndex, holding the position of the best brand seen so far. Start it at 0: with nothing else to compare against, the first brand is the best so far. Then look at positions 1 to the end. Each time a rating is strictly higher than the one at bestIndex, move bestIndex to that position.

    The program stores the position, not the rating itself, because one position reaches both arrays: brands[bestIndex] is the name and ratings[bestIndex] is its rating.

    The scan on the starter data

    indexratings[index]bestIndex after the check
    151
    231
    351
    441

    At position 3, the rating 5 is equal to the best, not strictly greater, so bestIndex stays at 1. That is how the tie goes to MegaCorp.

    Step by step

    1. Create bestIndex as a var set to 0. It will change, and for now the first brand is the best.
    2. Write the for loop over 1..<ratings.count. Position 0 is already the best so far, so the scan starts at 1. The loop variable is named index in the code.
    3. Inside the loop, add an if that tests whether this brand's rating is strictly greater than the rating at bestIndex.
    4. Inside the if, set bestIndex to the current position.
    5. After the loop, print the winner with interpolation: the rank 1. , the brand at bestIndex, a space and an opening parenthesis, the rating at bestIndex, then a closing parenthesis.

    The solution in Swift

            let brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
            let ratings = [4, 5, 3, 5, 4]
    
            var bestIndex = 0
            for index in 1..<ratings.count {
                if ratings[index] > ratings[bestIndex] {
                    bestIndex = index
                }
            }
            print("1. \(brands[bestIndex]) (\(ratings[bestIndex]))")
    

    The Swift details worth knowing:

    • Half-open range. 1..<ratings.count starts at 1 and stops before ratings.count. With five ratings the values are 1, 2, 3 and 4. The closed form 1...ratings.count would include 5, and ratings[5] is out of bounds, so it crashes at run time.
    • Expressions inside interpolation. \(brands[bestIndex]) and \(ratings[bestIndex]) hold whole subscript expressions. Any expression works inside the parentheses.
    • Arrays of one type. brands is a [String] and ratings is an [Int]. They are separate arrays that the program keeps in step by position, so they must have the same length.
    • Constants and variables. The arrays are lets, since the loop only reads them, while bestIndex is a var.

    Complexity

    Time: O(n). The loop visits each of the other n - 1 positions once and does a constant amount of work at each.

    Space: O(1). The program stores one integer, bestIndex, no matter how many brands there are.

    Edge cases and common mistakes

    • Ties. The strict > keeps the earlier brand. Changing it to >= makes the later brand replace it, and the starter data would then print 1. NeoByte (5).
    • One brand. With only ["TechPro"] and [4], the range 1..<1 is empty, the loop body doesn't run, and the program prints 1. TechPro (4).
    • No brands. With empty arrays, the range 1..<0 is invalid and brands[0] doesn't exist, so the program crashes. The lesson's data always has at least one brand.
    • Storing the rating instead of the position. You would know the top score but not which brand earned it.
    • Arrays of different lengths. If brands were shorter than ratings, the final subscript could go out of bounds. The loop uses ratings.count, so the two arrays must match.

    Testing

    • The starter data prints 1. MegaCorp (5).
    • Using >= in the comparison, the same data prints 1. NeoByte (5).
    • The single brand ["TechPro"] with ratings [4] prints 1. TechPro (4).
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free