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).
1def element_count():
2 count = {}
3 n = int(input("Enter number of elements: "))
4 print("Enter the elements:")
5 for _ in range(n):
6 x = int(input())
7 if x in count:
8 count[x] += 1
9 else:
10 count[x] = 1
11
12 # Example query
13 query = int(input("Enter element to query: "))
14 print(f"Element {query} appears {count.get(query, 0)} times")
15
16# Run the function
17element_count()
This Python script uses a dictionary to count the frequency of elements. The dictionary is updated as elements are read, providing an efficient means to retrieve counts.
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
This C program sorts the list of elements using qsort()
, then iterates over the sorted list to count consecutive occurrences of each number. It outputs the frequency of each unique element.