Problem overview
Count(int[] nums, int value) returns how many times value appears in nums. For nums = [1, 4, 2, 2, 5, 2] and value = 2, the number 2 appears three times, so the answer is 3.
The lesson asks you to write the loop yourself rather than call a ready-made counting function, because the point is to practise the pattern.
Approach: a counter that changes only on a match
There is no way to know the count without looking at every element, so the method has to visit each one exactly once. While visiting, it keeps a counter. For every element, ask a single question: is it equal to value? If so, add one to the counter. If not, do nothing.
Tracing the example, the counter goes 0, 0, 1, 2, 2, 3 as the loop passes 1, 4, 2, 2, 5, 2. When the loop ends, the counter holds the answer.
This is the basic "count what matches" pattern. Variations of it, such as counting even numbers, counting words longer than three letters or counting values above a limit, only change the condition inside the if.
Step by step
- Declare
answerand set it to 0. It must exist before the loop, so that it keeps its value from one pass to the next. Zero is correct if nothing ever matches. - Loop over the elements with
foreach.foreach (int num in nums)gives each element in turn in the variablenum. No index is needed, because only the values matter, not their positions. - Compare and count. Inside the loop,
if (num == value)checks the current element, andanswer++adds one to the counter when it matches. Elements that differ are skipped. - Return after the loop. The
return answer;line goes below the loop's closing brace. A return inside the loop would stop the method after the first element.
The solution in C#
class Solution {
public int Count(int[] nums, int value) {
int answer = 0;
foreach (int num in nums) {
if (num == value) {
answer++;
}
}
return answer;
}
}
A few C# points are worth noting:
==compares,=assigns.num == valueasks a question. Writingnum = valueinside theifdoesn't compile in C#, because an assignment to anintis not abool. The compiler catches the typo for you.answer++adds one toanswer. It is shorthand foranswer = answer + 1.foreachworks on any collection. It handles arrays and lists in the same way. Use an index-basedforloop only when you need the position of each element, as the next lessons do.- Arrays have a fixed length.
nums.Lengthnever changes, and the loop simply stops after the last element. An empty array is fine: the loop body doesn't run.
Complexity
Time: O(n). Each of the n elements is compared once, and each comparison and increment takes constant time. Every element has to be checked, so no counting method can do better on an unsorted array.
Space: O(1). The method uses the counter and the loop variable only.
Edge cases and common mistakes
- The value is missing. The condition is never true, and the method returns 0.
- An empty array. The loop doesn't run, and the method returns 0.
- Every element matches. For
[7, 7, 7]andvalue = 7the answer is 3, the array's length. - Stopping at the first match. This is the mistake of using the pattern from the "find an index" lessons. A
returninside theifwould report 1 at most. For counting, the loop has to run to the end. - Declaring the counter inside the loop. The counter would be recreated at 0 on every pass, and the method would not compile at the final
return, becauseanswerwould no longer be in scope there. - Forgetting the braces. Without braces an
ifcontrols only the next statement. It works for a single line, but adding a second line later is a classic source of bugs, so the braces are worth keeping.
Testing
[1, 4, 2, 2, 5, 2]with value 2 gives3.[1, 2, 3]with value 9 gives0.[7, 7, 7]with value 7 gives3.[]with value 1 gives0.[-1, 1, -1]with value -1 gives2.