Start learning free

LESSON 143 OF 410 · LOOPS & GLOBAL VARIABLES

Number of Occurrences in Array - Python Solution with O(n) Time Complexity

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

    PYTHON · LOOPS & GLOBAL VARIABLES

    Array Count in Python, explained

    Understanding the Problem: Count Without Built-Ins

    Counting how many times a value appears in a list is something Python's .count() method does in one line. But this challenge asks you to build that logic yourself — which reveals the fundamental pattern behind frequency counting: a loop and a counter variable. Once you internalize this pattern, you'll recognize it in dozens of algorithm problems.

    The Core Pattern: Loop + Counter

    Walk through every element. Each time you find a match, increment a counter. At the end, return the counter:

    1. Start with count = 0.
    2. Loop through every element in nums.
    3. If the element equals value, do count += 1.
    4. Return count.

    Code Implementation

    def count_occurrences(nums, value):
        count = 0
        for num in nums:
            if num == value:
                count += 1
        return count
    
    # Examples:
    print(count_occurrences([1, 4, 2, 2, 5, 2], 2))   # 3
    print(count_occurrences([1, 4, 2, 2, 5, 2], 5))   # 1
    print(count_occurrences([1, 4, 2, 2, 5, 2], 9))   # 0
    

    Why This Pattern Matters Beyond This Problem

    The counter accumulator pattern is everywhere in programming:

    # Count how many students passed (score >= 60):
    scores = [72, 45, 88, 55, 91, 60, 38]
    pass_count = 0
    for score in scores:
        if score >= 60:
            pass_count += 1
    print(f"{pass_count}/{len(scores)} students passed")   # 4/7 students passed
    
    # Count words in a sentence:
    words = "the quick brown fox jumps over the lazy fox"
    word_list = words.split()
    fox_count = 0
    for word in word_list:
        if word == "fox":
            fox_count += 1
    print(f"'fox' appears {fox_count} times")   # 'fox' appears 2 times
    

    Complexity Analysis

    • Time: O(n) — Every element is visited exactly once. There's no shortcut for an unsorted array — you must check everything.
    • Space: O(1) — Only one counter variable, regardless of input size. No extra data structures.

    This is optimal for an unsorted array. If the array were sorted, you could use binary search to find the first and last occurrence in O(log n) — but that's a more advanced technique.

    Edge Cases

    # Empty array — loop never runs, count stays 0:
    count_occurrences([], 5)             # 0
    
    # Value not present:
    count_occurrences([1, 2, 3], 9)      # 0
    
    # All elements match:
    count_occurrences([7, 7, 7, 7], 7)   # 4
    
    # Single element:
    count_occurrences([5], 5)            # 1
    count_occurrences([5], 3)            # 0
    

    Verify All Test Cases

    assert count_occurrences([1, 4, 2, 2, 5, 2], 2) == 3
    assert count_occurrences([], 2) == 0
    assert count_occurrences([1, 3, 4], 2) == 0
    assert count_occurrences([2, 2, 2], 2) == 3
    assert count_occurrences([1, 1, 1, 1, 1], 1) == 5
    print("All tests passed!")
    

    Key Takeaways

    • The loop + counter pattern is one of the most fundamental in programming — memorize it.
    • Initialize the counter to 0 before the loop; return it after.
    • Time complexity is O(n); space is O(1) — this is optimal for unsorted data.
    • The same pattern extends to counting anything: words, events, passing scores, errors.

    What to Learn Next

    Once you can count one value, the natural extension is counting all values simultaneously. Explore dictionaries to build a frequency map of every element in one pass — a pattern that powers many real-world algorithms from word frequency analysis to anagram detection.

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