LeetCode 75

Unique Number of Occurrences

Problem
LC 1207
Topic
Hash Map / Set
File
official75_LC1207UniqueNumberOfOccurrences.java
Path
pkg5leetcode/official75/official75_LC1207UniqueNumberOfOccurrences.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC1207UniqueNumberOfOccurrences.java
Approach
Count frequencies; set size equals max frequency count.
Complexity
Time O(n), Space O(n)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC1207UniqueNumberOfOccurrences.java
1package pkg5leetcode.official75;2 3/*4 * Unique Number of Occurrences | LC 12075 * APPROACH: Count frequencies; set size equals max frequency count.6 * COMPLEXITY: Time O(n), Space O(n)7 */8import java.util.*;9 10public class official75_LC1207UniqueNumberOfOccurrences {11    static boolean uniqueOccurrences(int[] arr) {12        Map<Integer, Integer> freq = new HashMap<>();13        for (int n : arr) freq.put(n, freq.getOrDefault(n, 0) + 1);14        Set<Integer> seen = new HashSet<>();15        for (int c : freq.values()) {16            if (!seen.add(c)) return false;17        }18        return true;19    }20 21    public static void main(String[] args) {22        check(uniqueOccurrences(new int[]{1,2,2,1,1,3}), "case1");23        check(!uniqueOccurrences(new int[]{1,2}), "case2");24        System.out.println("all tests passed");25    }26 27    static void check(boolean cond, String name) {28        if (!cond) throw new AssertionError("FAILED: " + name);29        System.out.println("  PASS " + name);30    }31}