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.
1#include <iostream>
2#include <unordered_map>
3using namespace std;
4
5void countElements(int arr[], int size) {
6 unordered_map<int, int> frequency;
7 for (int i = 0; i < size; i++) {
8 frequency[arr[i]]++;
9 }
10 for (auto& kvp : frequency) {
11 cout << "Element " << kvp.first << " appears " << kvp.second << " times\n";
12 }
13}
14
15int main() {
16 int arr[] = {1, 3, 1, 2, 3, 4, 5, 3};
17 int size = sizeof(arr) / sizeof(arr[0]);
18 countElements(arr, size);
19 return 0;
20}
This C++ solution utilizes the unordered_map from the STL for efficient insertion and lookup operations which can be achieved in average O(1) time. It simplifies the implementation compared to managing a manual hash table.
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.
1function countSortedElements(arr) {
2 arr.sort((a, b) => a - b);
3 let count = 1;
4 for (let i = 1; i < arr.length; i++) {
5 if (arr[i] === arr[i - 1]) {
6 count++;
7 } else {
8 console.log(`Element ${arr[i - 1]} appears ${count} times`);
9 count = 1;
10 }
11 }
12 console.log(`Element ${arr[arr.length - 1]} appears ${count} times`);
13}
14
15let arr = [1, 3, 1, 2, 3, 4, 5, 3];
16countSortedElements(arr);
This JavaScript code sorts the array and iterates through it to count occurrences of elements efficiently. Sorting groups duplicates together, aiding accurate counts.