easyBasic Hashing

Count frequency of array elements

Count the occurrences of each distinct value in an array.

Work through the cases

3 examples

Input notation

One nonempty line of space-separated integers.

Expected result

One value:count pair per line, ordered by increasing value.
Case 1

Input

3 1 3 2 1 3

Expected output

1:2
2:1
3:3
Case 2

Input

7 7

Expected output

7:2
Case 3

Input

-1 0 -1

Expected output

-1:2
0:1

These notes use simplified input/output notation. The linked platform defines the method signature and judge format.

FROM IDEA TO IMPLEMENTATION

Understand the approach.

Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.

Count each value in a map, then sort the keys for deterministic output. Time: O(n + k log k), extra space: O(k), where k is the number of distinct values.

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        ArrayList<Long> values = new ArrayList<>();
        while (in.hasNextLong()) values.add(in.nextLong());
        long[] a = values.stream().mapToLong(Long::longValue).toArray();
        long n = a[0];
        TreeMap<Long,Integer> counts = new TreeMap<>(); for (long v : a) counts.merge(v, 1, Integer::sum); counts.forEach((v,c) -> System.out.println(v + ":" + c));
    }
}

Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.