Start learning free

LESSON 146 OF 414 · LOOPS & GLOBAL VARIABLES

Counting Occurrences in an Array in Scala

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

    SCALA · LOOPS & GLOBAL VARIABLES

    Array Count in Scala, explained

    Problem overview

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

    The note asks you to write the loop yourself, not to call a ready-made counting function from the library. The point is to practise scanning an array.

    Approach: scan once and keep a tally

    You can't know the answer without looking at every element, because any of them might match. So the method walks the array from the first element to the last. It keeps a counter that starts at 0, and each time the current element equals value, the counter goes up by one. When the walk ends, the counter is the answer.

    Equal elements are counted separately, so duplicates cause no problem. The array doesn't need sorting.

    Step by step

    1. Declare var answer = 0. It must be a var, since a val can't be reassigned and the counter changes. Scala infers Int.
    2. Loop with for (num <- nums). The arrow <- is a generator: the body runs once per element, in order, with num holding the current one.
    3. Compare with if (num == value) and add one with answer += 1 on a match. Scala has no ++, so += 1 is the way to increment. The == operator compares values, which for Int is what you want.
    4. Return answer after the loop. Returning inside the loop would end the method after the first element.

    The solution in Scala

    class Solution {
        def count(nums: Array[Int], value: Int): Int = {
            var answer = 0
            for (num <- nums) {
                if (num == value) {
                    answer += 1
                }
            }
            return answer
        }
    }
    

    Tracing the example with value = 2:

    numEquals 2?answer afterwards
    1no0
    4no0
    2yes1
    2yes2
    5no2
    2yes3

    Language details

    • The loop variable num is a fresh val on each pass. You read it but can't assign to it, and changing the array isn't needed here.
    • The loop variable num and the parameter value are two different names. Keeping them distinct makes the comparison easy to read.
    • Because the if has no else, nothing happens for elements that don't match.

    Complexity

    The loop visits each of the n elements once and does a constant amount of work for each, so the time is O(n). Only answer and the loop variable are stored, so the extra space is O(1).

    Edge cases and common mistakes

    • The value is absent. No element matches, so the method returns 0.
    • An empty array. The loop body never runs and the method returns 0.
    • Every element matches. The method returns the array's length.
    • Returning inside the loop. The method would stop after the first element and report at most 1.
    • Using = instead of ==. Writing if (num = value) is an attempt to assign to the loop variable, and the compiler stops with the error Reassignment to val num.
    • Declaring answer inside the loop. It would reset to 0 on every pass and the final count would be 0 or 1.

    Testing

    Try Array(1, 4, 2, 2, 5, 2) with value 2 (3), Array(1, 2) with value 7 (0), Array(7, 7, 7) with value 7 (3) and an empty array (0).

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