Input: arr = [4, 2, 8, 3, 2, 7, 5, 2, 1, 2, 9, 2] target = 2 Output: The element 2 occurs 5 times in the array. Input: arr = [2, 8, 3, 3, 7, 5, 2, 1, 2, 2] target = 3 Output: The element 3 occurs 2 times in the array.
Count the Occurrence of Elements in an Array Using Linear Search.
- Initialize a counter variable to zero, which will be used to store the count of occurrences.
- Iterate through the array element by element.
- For each element encountered, check if it matches the target element for which we are counting occurrences.
- If the current element matches the target element, increment the counter.
- After the iteration, the counter variable contains the total count of occurrences.
# Python code to count occurrence of an element def count_occurrences(arr, target): count = 0 for element in arr: if element == target: count += 1 return count # drive arr = [2, 4, 5, 2, 2, 5, 1] target = 2 print('{} has occurred {} times'.format(target, count_occurrences(arr, target)))
2 has occurred 3 times- Time Complexity: O(n) where n is the length of the array.
- Space Complexity: O(1) as we use only a constant amount of extra space.
Count Occurrence of an Element in Array Using Counter Function.
- Import Counter function from Collection module.
- Apply the Counter function to the array to create a dictionary of element counts.
- Retrieve the count of the target element from the generated dictionary.
# Python code to count occurrence of an element using counter from collections import Counter def countTarget(arr, target): counts = Counter(arr) return counts[target] # drive arr = [2, 4, 5, 2, 2, 5, 1] target = 2 print('{} has occurred {} times'.format(target, countTarget(arr, target)))
2 has occurred 3 times- Time Complexity: O(n) where n is the length of the array.
- Space Complexity: O(n) where n is the number of unique elements in the array.
Count Occurrence of an Element in an Array Using list.count().
# Python code to count occurrence of an element in list def countTarget(arr, target): return arr.count(target) # drive arr = [2, 4, 5, 2, 2, 5, 1, 1] target = 1 print('{} has occurred {} times'.format(target, countTarget(arr, target)))
2 has occurred 3 times- Time Complexity: O(n^2) where n is the length of the array.
- Space Complexity: O(1) as only a constant amount of extra space is required.





Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.