Problem overview
The method count receives an array of integers, nums, and an integer value. It returns how many times value appears in the array. For nums = [1, 4, 2, 2, 5, 2] and value = 2, the 2 shows up at three positions, so the answer is 3.
The task asks you to write the loop yourself instead of calling a library function that counts for you.
Approach: a counter and one pass
Look at each element exactly once. Keep a counter that starts at zero, and every time the current element equals value, add one. After the last element, the counter holds the answer. There is no need to remember where the matches were, only how many there were.
On the example, the counter goes 0, 0, 0, 1, 1, 2: reading 1, 4, 2, 2, 5 and 2 in turn, it rises at each 2 and nowhere else, and ends at 3. The order of the elements doesn't matter, and neither do duplicates of other values.
This is also the cleanest model of a pattern you will use again and again: a variable declared before a loop, updated inside it under a condition, and read after it.
Step by step
- Declare the counter.
var answer = 0. It must be avarbecause it grows. Aletconstant could not be changed. - Loop over the elements.
for num in numsvisits each one in order, with no index to manage. - Compare and count. Inside the loop,
if num == valueguardsanswer += 1, so only matches are counted. - Return after the loop. The answer is only complete once every element has been looked at.
The solution in Swift
class Solution {
func count(_ nums: [Int], _ value: Int) -> Int {
var answer = 0
for num in nums {
if num == value {
answer += 1
}
}
return answer
}
}
Swift details worth knowing:
- No
++. Swift has no increment operator. Writinganswer++is a compile error that suggests+= 1. for ... in. The loop variablenumis a new constant on each pass, a copy of the element. Assigning to it inside the loop is not allowed.- Method name. The method is called
count, and arrays also have a property namedcount. They do not clash, because the method lives onSolutionand the property on the array. Inside the method,nums.countis still the array's length. - Underscore labels. Both parameters are declared with
_, so a call readscount([1, 4, 2, 2, 5, 2], 2), with no argument labels. - Types.
answeris inferred asIntfrom the literal0, which matches the return type.
Complexity
Time: O(n) for an array of n elements, since each is compared once.
Space: O(1). Only the counter and the loop variable are needed.
The same loop shape works for many counting tasks. Swap the condition num == value for num > value, num % 2 == 0 or any other test that gives a Bool, and the loop counts a different property of the elements.
Edge cases and common mistakes
- Empty array. The loop does nothing and the function returns
0. - Value not present. The counter never changes, so the result is
0. - Returning inside the loop. A
returnplaced in the loop body ends the function after the first element. - Setting instead of adding.
answer = 1in place ofanswer += 1makes every non-empty match count as one. - Putting the declaration inside the loop. A counter created on every pass restarts at zero each time.
Testing
nums = [1, 4, 2, 2, 5, 2],value = 2gives3.nums = [],value = 2gives0.nums = [1],value = 9gives0.
