Given an integer array nums and an integer target, return the number of times target appears in the array.
Example 1
Input: nums = [2, 4, 2, 5, 2, 7], target = 2
Output: 3
Explanation: The target element 2 appears at index 0, index 2, and index 4. So, the frequency is 3.
Example 2
Input: nums = [10, 20, 30, 40], target = 50
Output: 0
Explanation: The target element 50 is not present in the array. So, the frequency is
Approach
Traverse the array and maintain a counter for the occurrences of target.
Whenever the current element equals target, increment the counter. After every element has been checked, the counter represents the required frequency.
Algorithm
Initialize
countwith0, where it keeps track of how many timestargethas been found so far.Traverse every element of
numsso that no possible occurrence oftargetis missed.Compare the current element with
target. If both values are equal, incrementcountbecause one more occurrence has been found.Return
countafter the complete array has been checked, as it now represents the total frequency oftarget.
Dry Run
Count Freq Dry Run .png
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: int countFrequency(const vector<int>& nums, int target) { // Stores the number of target occurrences found so far. int count = 0; for (int value : nums) { // Only values equal to target contribute to its frequency. if (value == target) { count++; } } return count; }};int main() { vector<int> nums = {2, 3, 2, 5, 2}; int target = 2; Solution solution; int answer = solution.countFrequency(nums, target); cout << "Frequency of target: " << answer << endl; return 0;}Complexity Analysis
Time Complexity: O(N), where N represents the number of elements in the array. Every element is compared with target once.
Space Complexity: O(1), because only the count variable requires auxiliary storage.
Interview follow-up Questions
The result is 0 because no matching element is found.
Be the first to add a comment.