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.
1import java.util.HashMap;
2
3public class ElementCounter {
4 public static void countElements(int[] arr) {
5 HashMap<Integer, Integer> frequency = new HashMap<>();
6 for (int num : arr) {
7 frequency.put(num, frequency.getOrDefault(num, 0) + 1);
8 }
9 for (var entry : frequency.entrySet()) {
10 System.out.println("Element " + entry.getKey() + " appears " + entry.getValue() + " times");
11 }
12 }
13
14 public static void main(String[] args) {
15 int[] arr = {1, 3, 1, 2, 3, 4, 5, 3};
16 countElements(arr);
17 }
18}
In Java, a HashMap is used, which efficiently handles the counting of each element's frequency. The getOrDefault method simplifies handling new and existing keys in the map.
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.
1def count_sorted_elements(arr):
2 arr.sort()
3 count = 1
4 for i in range(1, len(arr)):
5 if arr[i] == arr[i - 1]:
6 count += 1
7 else:
8 print(f'Element {arr[i - 1]} appears {count} times')
9 count = 1
10 print(f'Element {arr[-1]} appears {count} times')
11
12arr = [1, 3, 1, 2, 3, 4, 5, 3]
13count_sorted_elements(arr)
This Python method sorts the array and iterates through it to count appearances of each number. The sorted array ensures that duplicates are counted consecutively.