Unique and Count
Problem Statement
Find unique elements and their counts in a NumPy array.
Background
- np.unique(arr): Returns sorted unique elements
- np.unique(arr, return_counts=True): Also returns count of each element
Your Task
Write a function unique_count(arr) that returns a dictionary with:
- "unique": Unique elements (sorted) as list
- "counts": Count of each unique element as list
- "num_unique": Number of unique elements
Output Format
Return a dictionary with exactly these three keys.
Example:
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
{'unique': [1, 2, 3, 4], 'counts': [1, 2, 3, 4], 'num_unique': 4}1 appears once, 2 twice, 3 three times, 4 four times
Constraints:
- Use np.unique() with return_counts=True
- Array will have at least 1 element
1. Background Knowledge
NumPy arrays provide efficient multidimensional array objects for numerical computing in Python, enabling vectorized operations that avoid Python loops for better performance. The np.unique() function identifies distinct elements in an array and optionally returns their frequencies, making it ideal for this problem.
Key prerequisites:
- Basic NumPy array creation and manipulation
- Understanding return_counts=True parameter behavior
- Python dictionary construction with specific key-value pairs
Mathematical foundation: For an array A of size n with k unique elements, np.unique(A, return_counts=True) returns sorted unique values U=[u1,u2,…,uk] and counts C=[c1,c2,…,ck] where \sumci=n and each ui appears exactly ci times.
2. Algorithm Approach
Direct use of np.unique() with return_counts=True is the optimal approach per constraints. This leverages NumPy's internal sorting + counting algorithm:
Input: arr = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
Step 1: Sort → [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
Step 2: Scan for runs → unique=[1,2,3,4], counts=[1,2,3,4]
Alternative approaches (not recommended here):
- Manual sorting + counting: O(nlogn) time, redundant
- Hash tables: O(n) expected time, loses sorted order
- np.bincount(): Requires integer indices, doesn't sort
3. Step-by-Step Strategy
def unique_count(arr):
# Step 1: Get unique elements and counts in one call
unique_elements, counts = np.unique(arr, return_counts=True)
# Step 2: Compute number of unique elements
num_unique = len(unique_elements)
# Step 3: Package into required dictionary format
return {
"unique": unique_elements.tolist(), # Convert to Python list
"counts": counts.tolist(), # Convert to Python list
"num_unique": num_unique
}
Why this works:
- np.unique() automatically sorts output
- .tolist() converts NumPy arrays to native Python lists for dictionary
- Dictionary keys match exact specification
4. Common Pitfalls
| Pitfall | Problem | Fix |
|---|---|---|
| Forgetting .tolist() | NumPy arrays in dict → serialization issues | Always use .tolist() for dictionary values |
| Returning NumPy arrays directly | Fails output format requirement | Convert with .tolist() |
| Using return_index=True | Wrong parameter for counts | Use return_counts=True |
| Manual loop implementation | Violates constraints, slower | Use np.unique() directly |
| Missing import numpy as np | NameError | Always import NumPy |
Edge cases to test:
# Single element
np.array() → {'unique':, 'counts':, 'num_unique': 1}
# All duplicates
np.array([2, 2, 2]) → {'unique':, 'counts':, 'num_unique': 1}
# Already sorted/unsorted
np.array([3, 1, 3, 2]) → {'unique': [1, 2, 3], 'counts': [1, 1, 2], 'num_unique': 3}
5. Time & Space Complexity
Time Complexity: O(nlogn)
- np.unique() internally sorts array: O(nlogn)
- Single linear pass for counting: O(n)
- Dominant term: O(nlogn) due to sorting
Space Complexity: O(n)
- Output arrays store k≤n unique elements + counts
- Temporary sorting buffer: O(n)
- Total: O(n) worst case (all unique elements)
Why efficient: NumPy's C implementation + vectorization provides significant speedup over pure Python (often 100x+).
Complete Solution
import numpy as np
def unique_count(arr):
"""Return dictionary with sorted unique elements, their counts, and count of uniques."""
unique_elements, counts = np.unique(arr, return_counts=True)
return {
"unique": unique_elements.tolist(),
"counts": counts.tolist(),
"num_unique": len(unique_elements)
}
# Test
arr = np.array([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
print(unique_count(arr))
# {'unique': [1, 2, 3, 4], 'counts': [1, 2, 3, 4], 'num_unique': 4}
This solution is constraint-compliant, efficient, and robust across all valid inputs.