Random choice from array in NumPy - Time & Space Complexity
We want to understand how the time it takes to pick a random item from an array changes as the array grows.
How does the size of the array affect the speed of choosing a random element?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.arange(1000)
choice = np.random.choice(arr)
print(choice)
This code creates an array of numbers from 0 to 999 and picks one random number from it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing one random index in the array.
- How many times: Exactly once per call.
Picking one random element does not require checking all elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of operations stays the same no matter how big the array is.
Time Complexity: O(1)
This means picking a random element takes the same amount of time no matter how large the array is.
[X] Wrong: "Choosing a random element takes longer if the array is bigger because it has more items to look through."
[OK] Correct: The method directly picks an index without scanning the whole array, so the size does not affect the time.
Understanding constant time operations like random choice helps you explain efficient data access in real projects.
"What if we wanted to pick multiple random elements without replacement? How would the time complexity change?"