Frequency Peaks and Prime Extraction
Math & Bit ManipulationAuto-graded · 19 test casesLast updated
Tests frequency counting with tie-aware mode detection and prime identification via sieve, including edge cases for unique values and non-prime inputs.
Frequency Peaks and Prime Extraction
You are building a statistical utility module that needs two analysis routines over integer arrays. Implement a single function that returns both results in one pass.
Task
Given a list of integers nums, return a dictionary with exactly two keys:
"mode" — the most frequently occurring value(s):
- If
numsis empty, or if every value innumsappears exactly once, set"mode"toNone. - Otherwise, collect every value tied for the highest frequency. Return them as a sorted list, even when only one value qualifies (e.g.,
[3]not3).
"primes" — the prime values present in the list:
- Identify every value in
numsthat is a prime number. - Return a sorted list of distinct such values.
- Values less than 2 (including negatives, zero, and one) are never prime and must be excluded.
- If no primes exist, return an empty list
[].
Notes
- Both sub-problems operate on the same input list but are fully independent of each other.
- Duplicate values in
numsstill count as a single entry in"primes"(deduplication required). - A list with a single element always has all-unique values, so its
"mode"isNone. - The
"mode"result is a list orNone— never a bare integer.
Constraints
0 ≤ len(nums) ≤ 10^5-10^6 ≤ nums[i] ≤ 10^6- The function must not mutate the input list.
- Both lists in the output must be sorted in ascending order.
Examples
Example 1
Input: frequency_peaks_and_primes([1, 2, 2, 3, 4, 4, 5])
Output: {'mode': [2, 4], 'primes': [2, 3, 5]}
Example 2
Input: frequency_peaks_and_primes([1, 2, 3, 4, 5])
Output: {'mode': None, 'primes': [2, 3, 5]}
Example 3
Input: frequency_peaks_and_primes([1, 1, 2, 2, 3, 3, 5, 7])
Output: {'mode': [1, 2, 3], 'primes': [2, 3, 5, 7]}
Example 4
Input: frequency_peaks_and_primes([6, 8, 9, 10])
Output: {'mode': None, 'primes': []}
Hints
Hint 1
For the mode, a single pass with a frequency map gives you everything you need: the counts, the maximum count, and whether that maximum is greater than 1.
Hint 2
For primes, consider whether trial division per element or a sieve over the range up to max(nums) is more efficient when values are densely packed — and think about what to do if no element is ≥ 2.
Hint 3
Watch the edge cases: an empty input, a list where every value appears once (mode is None, not an empty list), the number 1 (not prime), and negative numbers (they can be modes but never primes).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two sub-problems share only the input list; they are otherwise independent, so each can be solved with the standard tool for it.
Mode: frequency counting
Use a Counter to tally how many times each value appears — one linear pass through nums. Then:
- If the counter is empty (empty input), the mode is
None. - Find the highest count.
- If that highest count is
1, every value appeared exactly once, so the mode isNone. - Otherwise, collect every value whose count equals the highest, sort the result, and return it as a list.
Sorting makes the output deterministic regardless of the order values were inserted into the hash map.
Primes: Sieve of Eratosthenes
First deduplicate by building a set of every value ≥ 2 (negatives, zero, and one are never prime). If the set is empty, return [].
Let M = max(candidates). Allocate a bytearray of length M + 1, initialised to 1 (meaning "assumed prime"). Set positions 0 and 1 to 0. Then iterate over every factor from 2 up to √M:
- If
factoris still marked prime, cross out every multiple starting atfactor². Any smaller multiplek · factorwithk < factorhas a prime factor less thanfactorand was already eliminated, so starting atfactor²is correct and avoids redundant work.
After the loop, is_prime[v] is 1 exactly when v is prime. Filter the sorted candidate set by this flag.
Using a bytearray with slice assignment means the crossing-out work runs at C speed rather than in a Python loop, which matters when M is large.
Why this is correct
Mode. Counter records exact frequencies. The "all unique" condition is precisely equivalent to "maximum frequency equals 1," so that single check covers both the one-element case and any list where no value repeats.
Sieve. Every composite number c ≤ M has a smallest prime factor p where p² ≤ c. When the outer loop reaches p, it is still marked prime (nothing smaller divides it), and the slice assignment crosses out c. Primes are never crossed out because no number in [2, √p] divides them.
Complexity
Let n = len(nums), d = number of distinct values, M = max(nums) (for elements ≥ 2).
| Step | Time | Space |
|---|---|---|
| Frequency count | O(n) | O(d) |
| Mode selection + sort | O(d + k log k), k = mode count | O(k) |
| Build candidate set | O(n) | O(d) |
| Sieve | O(M log log M) | O(M) bytes |
Total time: O(n + d log d + M log log M), effectively O(n log n) under the "1 to n" input model. Total space: O(d + M), effectively O(n).
One trade-off worth knowing: if nums could contain a handful of very large values (say 10¹²), allocating a sieve up to M is infeasible. In that case, trial division in O(√v) per value — or a Miller–Rabin primality test — is the right substitute.
Edge cases
| Input | "mode" | "primes" |
|---|---|---|
[] | None | [] |
[7] | None | [7] |
[1, 2, 3, 4] | None | [2, 3] |
[2, 2, 3, 3, 5] | [2, 3] | [2, 3, 5] |
[4, 4, 4, 1] | [4] | [] |
[-5, 0, 1, -5] | [-5] | [] |
[9, 25, 49] | None | [] |
Full solution
from collections import Counter
from typing import List, Dict
def frequency_peaks_and_primes(nums: List[int]) -> Dict[str, object]:
# ---------- Mode ----------
counts = Counter(nums)
if not counts:
modes = None
else:
highest = max(counts.values())
# If the highest frequency is 1, every value is unique -> None.
# Otherwise collect all values tied at the top and sort them.
modes = None if highest == 1 else sorted(
value for value, count in counts.items() if count == highest
)
# ---------- Primes (Sieve of Eratosthenes) ----------
candidates = {value for value in nums if value >= 2}
if not candidates:
primes = []
else:
limit = max(candidates)
# One byte per index; bytearray lets slice assignment run at C speed.
is_prime = bytearray(b'\x01') * (limit + 1)
is_prime[0:2] = b'\x00\x00' # 0 and 1 are not prime
factor = 2
while factor * factor <= limit:
if is_prime[factor]:
# Cross out factor^2, factor^2+factor, ... in a single slice write.
is_prime[factor * factor:limit + 1:factor] = (
b'\x00' * (((limit - factor * factor) // factor) + 1)
)
factor += 1
primes = [value for value in sorted(candidates) if is_prime[value]]
return {"mode": modes, "primes": primes}