L1 · FoundationsList basics~1 min · 4 tests

Count Occurrences of an Element

Count how many times a value appears in a Python list with a loop, and compare with list.count(). Linear search basics with live tests in your browser.

The problem

Return how many times target appears in nums, without list.count().

Examples

  1. Example 1

    Input

    count_of([1, 2, 2, 3, 2], 2)

    Expected output

    3
  2. Example 2

    Input

    count_of([1, 2, 3], 9)

    Expected output

    0

+ 2 hidden tests on Submit.

Edge cases to ask about

  • Not present
  • Empty list

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · count_of
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    Measure it

    Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    Scan and countO(n)O(1)
    Walkthrough of the optimal approach (try it yourself first)

    One pass, one counter. If you need counts for many different targets, build a frequency dict once (O(n)) instead of scanning again for each one — that is the bridge to L2.

    Complexity: O(n) time, O(1) space. Every element is compared once.

    Reveal the reference solution
    def count_of(nums, target):
        count = 0
        for x in nums:
            if x == target:
                count += 1
        return count

    Follow-ups interviewers ask

    • Counts for every distinct value at once.

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Count Occurrences of an Element in Python?

    The optimal solution runs in O(n) time and O(1) auxiliary space. Every element is compared once.

    What follow-up questions do interviewers ask about Count Occurrences of an Element?

    Counts for every distinct value at once.