This approach involves using a HashMap (or dictionary in Python) to count the occurrences of each element in the array. This will help in efficiently checking if an element exists and how many times it appears, which is useful for problems requiring frequency analysis.
Time Complexity: O(n), as it iterates over the array once. Space Complexity: O(1) if the element range is known and constant, or O(k) where k is the range of elements.
1function countElements(arr) {
2 let frequency = {};
3 arr.forEach(num => {
4 frequency[num] = (frequency[num] || 0) + 1;
5 });
6 for (let key in frequency) {
7 console.log(`Element ${key} appears ${frequency[key]} times`);
8 }
9}
10
11let arr = [1, 3, 1, 2, 3, 4, 5, 3];
12countElements(arr);
In JavaScript, the frequency of each element is tracked using an object as a hash map. The forEach method efficiently processes the array, and the object properties hold frequencies.
Another approach is sorting the array and then identifying repeated elements by comparison with neighboring elements. This leverages the efficiency of modern sorting algorithms to bring repeated elements together, making it trivial to count consecutive duplicates.
Time Complexity: O(n log n) due to the sort operation. Space Complexity: O(1) if in-place sorting is considered.
1#include <iostream>
2#include <algorithm>
3using namespace std;
4
5void countSortedElements(int arr[], int size) {
6 sort(arr, arr + size);
7 int count = 1;
8 for (int i = 1; i < size; i++) {
9 if (arr[i] == arr[i - 1]) {
10 count++;
11 } else {
12 cout << "Element " << arr[i - 1] << " appears " << count << " times\n";
13 count = 1;
14 }
15 }
16 cout << "Element " << arr[size - 1] << " appears " << count << " times\n";
17}
18
19int main() {
20 int arr[] = {1, 3, 1, 2, 3, 4, 5, 3};
21 int size = sizeof(arr) / sizeof(arr[0]);
22 countSortedElements(arr, size);
23 return 0;
24}
C++ provides a convenient sort function via the algorithm header, making it easy to arrange elements and subsequently count them by comparison of neighbors.