Workspace Count Occurrences
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Count Occurrences visualizer

Count all positions that contain the target value.

EXECUTION LAB

Count all positions that contain the target value.

Input and constraints
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
i = 0
count = 0
while (i < len(values)):
if (values[i] == target):
count = (count + 1)
i = (i + 1)
return count

Visualizer

Step 1 of 5
04i
12
24
34

Test the next value against the current value

Test the next value against 4. The count so far is 0.

Variable watch

i 0count 0target 4

Step explanation

Test the next value against 4. The count so far is 0.

comparisons 1reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(1) space

Worked explanation

A ticket checker makes one tally mark for each passenger on a list.

Guided solution

Keep a count of matches in the prefix already inspected.

O(n) time · O(1) auxiliary space

Examples

Worked example · {"values":[4,2,4,4],"target":4} ⇒ 3

Edge case 1 · {"values":[],"target":3} ⇒ 0

Edge case 2 · {"values":[1,1],"target":0} ⇒ 0

Progressive hints

Hint 1A ticket checker makes one tally mark for each passenger on a list.
Hint 2Keep a count of matches in the prefix already inspected.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Finding the first match does not finish the count.

Interview follow-up

What changes if the input is sorted?

Continue learning

Practice related DSA questions in the same topic.