Start learning free

LESSON 146 OF 415 · LOOPS & GLOBAL VARIABLES

Array Count in Swift: Counting Occurrences with a Loop

Practice Read the full explanation

Given an array of integers nums, count and return the number of occurrences of a given value.

Example:

Input: nums = [1, 4, 2, 2, 5, 2], value = 2
Output: 3
Explanation: the value 2 appears 3 times in the array

Note:

Do not use builtin functions, it would defy the purpose of the challenge. Write the whole code yourself.

STEP 1 OF 4
    Ctrl + Enter to check

    SWIFT · LOOPS & GLOBAL VARIABLES

    Array Count in Swift, explained

    Problem overview

    The method count receives an array of integers, nums, and an integer value. It returns how many times value appears in the array. For nums = [1, 4, 2, 2, 5, 2] and value = 2, the 2 shows up at three positions, so the answer is 3.

    The task asks you to write the loop yourself instead of calling a library function that counts for you.

    Approach: a counter and one pass

    Look at each element exactly once. Keep a counter that starts at zero, and every time the current element equals value, add one. After the last element, the counter holds the answer. There is no need to remember where the matches were, only how many there were.

    On the example, the counter goes 0, 0, 0, 1, 1, 2: reading 1, 4, 2, 2, 5 and 2 in turn, it rises at each 2 and nowhere else, and ends at 3. The order of the elements doesn't matter, and neither do duplicates of other values.

    This is also the cleanest model of a pattern you will use again and again: a variable declared before a loop, updated inside it under a condition, and read after it.

    Step by step

    1. Declare the counter. var answer = 0. It must be a var because it grows. A let constant could not be changed.
    2. Loop over the elements. for num in nums visits each one in order, with no index to manage.
    3. Compare and count. Inside the loop, if num == value guards answer += 1, so only matches are counted.
    4. Return after the loop. The answer is only complete once every element has been looked at.

    The solution in Swift

    class Solution {
        func count(_ nums: [Int], _ value: Int) -> Int {
            var answer = 0
            for num in nums {
                if num == value {
                    answer += 1
                }
            }
            return answer
        }
    }
    

    Swift details worth knowing:

    • No ++. Swift has no increment operator. Writing answer++ is a compile error that suggests += 1.
    • for ... in. The loop variable num is a new constant on each pass, a copy of the element. Assigning to it inside the loop is not allowed.
    • Method name. The method is called count, and arrays also have a property named count. They do not clash, because the method lives on Solution and the property on the array. Inside the method, nums.count is still the array's length.
    • Underscore labels. Both parameters are declared with _, so a call reads count([1, 4, 2, 2, 5, 2], 2), with no argument labels.
    • Types. answer is inferred as Int from the literal 0, which matches the return type.

    Complexity

    Time: O(n) for an array of n elements, since each is compared once.

    Space: O(1). Only the counter and the loop variable are needed.

    The same loop shape works for many counting tasks. Swap the condition num == value for num > value, num % 2 == 0 or any other test that gives a Bool, and the loop counts a different property of the elements.

    Edge cases and common mistakes

    • Empty array. The loop does nothing and the function returns 0.
    • Value not present. The counter never changes, so the result is 0.
    • Returning inside the loop. A return placed in the loop body ends the function after the first element.
    • Setting instead of adding. answer = 1 in place of answer += 1 makes every non-empty match count as one.
    • Putting the declaration inside the loop. A counter created on every pass restarts at zero each time.

    Testing

    • nums = [1, 4, 2, 2, 5, 2], value = 2 gives 3.
    • nums = [], value = 2 gives 0.
    • nums = [1], value = 9 gives 0.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free