Start learning free

LESSON 141 OF 348 · LOOPS & GLOBAL VARIABLES

Number of Occurrences in an Array in Kotlin: A Counting 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

    KOTLIN · LOOPS & GLOBAL VARIABLES

    Array Count in Kotlin, explained

    Problem overview

    The function count receives an IntArray named nums and an Int named value. It returns how many elements of nums are equal to value. The statement asks you to write the loop yourself instead of calling a built-in counting function.

    In the example, nums = [1, 4, 2, 2, 5, 2] and value = 2. The number 2 sits at three positions, so the function returns 3.

    Approach: look at every element once

    An array has no shortcut for this question. To know how many elements equal value, you have to examine each one. So the plan is simple: keep a counter that starts at zero, walk through the array, and add one each time an element matches.

    The array is not sorted, and the elements can repeat in any order, so a match can be anywhere. Each element is examined once, so the time grows in step with the array length. Only the counter is stored in addition to the input, so the extra space is constant.

    Step by step

    1. Declare the counter. var answer = 0 holds the count so far. It must be a var, since a val can't change after it is set.
    2. Loop over the elements with for (num in nums). Each pass gives you the next element in num, so every element is visited exactly once, in order, and you don't need an index.
    3. Compare and count. Inside the loop, an if checks whether num == value. Only on a match does the code run answer++. Elements that differ are skipped, and the loop moves on.
    4. Return after the loop. The total is known only when all elements have been checked. A return inside the loop would end the function after the first element.

    The solution in Kotlin

    class Solution {
        fun count(nums: IntArray, value: Int): Int {
            var answer = 0
            for (num in nums) {
                if (num == value) {
                    answer++
                }
            }
            return answer
        }
    }
    

    The Kotlin details behind it:

    • == compares values. In Kotlin, == calls equals, so for numbers it asks whether they are equal. The reference-identity operator is ===, which you don't need here. Writing a single = inside the condition does not compile, because an assignment is not a Boolean expression.
    • for (num in nums). The loop variable is declared by the loop and is read-only inside the body. If you need positions as well as values, loop over nums.indices or use withIndex() instead.
    • answer++. It adds 1 to a var. answer += 1 means the same.
    • IntArray. It is Kotlin's array of primitive Int values, so the elements are compared directly and the array can't contain null.
    • Built-ins exist. Kotlin's standard library offers nums.count { it == value }. The lesson asks you not to use it, because the point is to practise the loop.

    Complexity

    Let n be the length of nums.

    Time: O(n). The loop does one comparison per element, and no more than one increment per element.

    Space: O(1). Only answer and the loop variable are stored, and neither depends on n.

    Edge cases and common mistakes

    • The value is absent. The counter never moves, and the function returns 0.
    • An empty array. The loop body never runs, so the result is 0.
    • Every element matches. intArrayOf(3, 3, 3) with value = 3 returns 3, the array length.
    • Negative values. intArrayOf(-1, 1, -1) with value = -1 returns 2. Nothing special is needed.
    • Returning inside the loop. The function would stop after the first element and return 0 or 1.
    • Resetting the counter. Declaring answer inside the loop creates a fresh zero on every pass, so the count never builds up.
    • Incrementing without the check. If answer++ sits outside the if, the function returns the array length.

    Testing

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