np.unique() for unique elements in NumPy - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how the time to find unique elements in an array changes as the array gets bigger.
How does the work grow when we ask numpy to find unique values?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.array([3, 1, 2, 3, 4, 2, 1])
unique_vals = np.unique(arr)
print(unique_vals)
This code finds all unique values in the array arr and returns them sorted.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting the array elements internally.
- How many times: The sorting process compares elements multiple times, roughly proportional to n log n, where n is the number of elements.
As the array size grows, the sorting step takes more time, but not just straight doubling.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 to 40 operations |
| 100 | About 600 to 700 operations |
| 1000 | About 10,000 to 12,000 operations |
Pattern observation: The operations grow a bit faster than the input size, roughly like n times log n.
Time Complexity: O(n log n)
This means the time to find unique elements grows a bit faster than the size of the array, because sorting takes extra steps.
[X] Wrong: "Finding unique elements takes time proportional only to the number of elements (O(n))."
[OK] Correct: Because numpy sorts the array internally to find unique values, the sorting step adds extra work, making it grow faster than just the number of elements.
Understanding how numpy finds unique elements helps you explain efficiency when working with data. It shows you can think about what happens behind the scenes, which is a useful skill in data science.
"What if the input array was already sorted? How would the time complexity of np.unique() change?"
Practice
np.unique() function do when applied to a NumPy array?Solution
Step 1: Understand the purpose of np.unique()
The functionnp.unique()extracts all different values from the input array and sorts them.Step 2: Compare with other options
Options A, B, and D describe different functions like shape, sum, and max, which are not whatnp.unique()does.Final Answer:
Returns all unique elements sorted from the array -> Option DQuick Check:
np.unique() = unique sorted elements [OK]
- Thinking it returns counts by default
- Confusing with sum or max functions
- Assuming it returns unsorted unique values
arr?Solution
Step 1: Recall the correct function call
The correct way to call the unique function in NumPy isnp.unique(arr).Step 2: Identify incorrect syntax
Options A, B, and C are invalid because either the method does not exist on the array object or the function is not called from the NumPy module correctly.Final Answer:
np.unique(arr) -> Option AQuick Check:
Use np.unique(array) syntax [OK]
- Trying to call unique as a method on array
- Forgetting the np. prefix
- Using a non-existent unique() function without np
import numpy as np arr = np.array([3, 1, 2, 3, 2, 1, 4]) result = np.unique(arr) print(result)
Solution
Step 1: Apply np.unique() to the array
The function extracts unique values from the array: 1, 2, 3, and 4.Step 2: Note the sorting behavior
np.unique() returns these unique values sorted in ascending order: [1 2 3 4].Final Answer:
[1 2 3 4] -> Option CQuick Check:
Unique sorted values = [1 2 3 4] [OK]
- Expecting original order instead of sorted
- Including duplicates in output
- Confusing with counts output
arr but raises an error. What is the error?import numpy as np arr = np.array([5, 6, 5, 7]) result = arr.unique() print(result)
Solution
Step 1: Identify the method call on the array
The code callsarr.unique(), but NumPy arrays do not have a method namedunique().Step 2: Understand the correct usage
The correct function isnp.unique(arr), a function in the NumPy module, not a method of the array object.Final Answer:
'numpy.ndarray' object has no attribute 'unique' -> Option AQuick Check:
Arrays have no unique() method [OK]
- Calling unique() as a method on array
- Forgetting to import numpy as np
- Using wrong function name or syntax
arr = np.array([[1, 2, 2], [3, 1, 4]]), which code correctly finds all unique elements in the entire array?Solution
Step 1: Understand np.unique() on 2D arrays
Callingnp.unique(arr)flattens the array and returns all unique elements sorted.Step 2: Check axis parameter effects
Usingaxis=0oraxis=1returns unique rows or columns, not unique elements overall.Step 3: Identify invalid method call
arr.unique()is invalid because arrays do not have a unique method.Final Answer:
np.unique(arr) -> Option BQuick Check:
np.unique(array) finds all unique elements [OK]
- Using axis parameter expecting unique elements, but it returns unique rows/columns
- Calling unique() as a method on array
- Confusing unique elements with unique rows or columns
