Sponsored
Sponsored
This approach uses a hash map (or dictionary) to count occurrences of elements in the data. By iterating through the data once to populate the hash map, we can achieve efficient lookups. The main idea is to traverse the input list, counting occurrences of each element, and storing these counts in a hash map for quick access in the future.
Time Complexity: O(n) for traversing the list once.
Space Complexity: O(k), where k is the range of input values (determined by MAX).
1function elementCount() {
2 let count = {};
3 let n = parseInt(prompt("Enter number of elements:"));
4 console.log("Enter the elements:");
5 for (let i = 0; i < n; i++) {
6 let x = parseInt(prompt());
7 if (count[x]) {
8 count[x]++;
9 } else {
10 count[x] = 1;
11 }
12 }
13
14 // Example query
15 let query = parseInt(prompt("Enter element to query:"));
16 alert(`Element ${query} appears ${count[query] || 0} times`);
17}
18
19elementCount();
This JavaScript function uses an object as a hash map for counting element occurrences. It reads user input through prompt()
and displays results using alert()
.
By sorting the input list, elements of the same value will be grouped together. We can then iterate through the sorted list to count the occurrences of each element. This takes advantage of the property of sorting to simplify the counting process.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1) additional space for counting.
1
Using Python's built-in sort()
method, this script sorts elements, then iterates over the sorted list to count and print occurrences.