Find Minimum and Mode of an Integer Array
Arrays & HashingAuto-graded · 21 test casesLast updated
Find the minimum element and the most frequent element (mode) in an unsorted list of integers.
Given a list of integers a, calculate two values:
- The minimum value present in
a. - The mode (the most frequently occurring element) in
a.
If the list is empty, return [None, None].
If multiple distinct numbers tie for the highest frequency, any of those numbers is an acceptable mode.
Constraints
- $0 \le \text{len}(a) \le 10^5$
- $-10^9 \le a[i] \le 10^9$ for each element $a[i]$
Output Format
Return a 2-element list [min_value, mode_value]. If a is empty, return [None, None].
Examples
Example 1
Input: minimum_and_mode([1, 2, 2, 3, 3, 3, 4])
Output: [1, 3]
Example 2
Input: minimum_and_mode([-5, -1, -5, 2, -1, -5])
Output: [-5, -5]
Example 3
Input: minimum_and_mode([7])
Output: [7, 7]
Hints
Hint 1
Handle the empty array base case first by returning `[None, None]`.
Hint 2
The minimum value can be found in $O(N)$ time with a single pass or built-in function.
Hint 3
To find the mode in $O(N)$ expected time, count element frequencies using a standard hash map or dictionary, then find the element with the highest count.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To compute both the minimum element and the mode of an input array:
- Edge Case: Check if the array
ais empty. If it is, return[None, None]. - Minimum: Scan through the array to locate the smallest element. Python's built-in
min(a)performs this linear scan in $O(N)$ time and $O(1)$ space. - Mode: Count the frequency of every unique integer in
ausing a frequency map orcollections.Counter. After populating frequencies, find the key associated with the maximum frequency count.
Complexity
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the number of elements in array
a. Computing the minimum takes $O(N)$ time. Building the frequency hash map takes $O(N)$ expected time, and finding the key with the maximum frequency takes $O(K)$ time where $K \le N$ is the number of distinct elements. - Space Complexity: $\mathcal{O}(N)$ space to store frequency counts for up to $N$ unique elements in the hash map.
Python Reference Solution
from typing import List, Optional
from collections import Counter
def minimum_and_mode(a: List[int]) -> List[Optional[int]]:
if not a:
return [None, None]
# Find minimum: O(N) time, O(1) space
min_val = min(a)
# Find mode using hash map counting: O(N) time, O(N) auxiliary space
counts = Counter(a)
mode_val = max(counts, key=counts.get)
return [min_val, mode_val]