1. Linear Frequency Counting
Intuition
Loop through all elements from index 0 to n - 1. If arr[i] == x, increment count. Return count at the end.
When to apply: Unsorted collections.
Algorithm
- Step 1: Initialize count = 0.
- Step 2: Iterate through all elements in arr.
- Step 3: If arr[i] == x, increment count by 1.
- Step 4: Return count.
#include <iostream>#include <vector> using namespace std; int countOccurrences(const vector<int>& arr, int x) { int count = 0; for (int num : arr) { if (num == x) count++; } return count;} int main() { vector<int> arr = {1, 1, 2, 2, 2, 2, 3}; cout << "Linear count of 2: " << countOccurrences(arr, 2) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Scans all N elements linearly. - Space complexity:
O(1)— Uses a single integer counter.