np.searchsorted() for insertion points 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 needed to find insertion points grows as the input size increases when using np.searchsorted().
How does the number of operations change when we search in bigger arrays?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.sort(np.random.randint(0, 1000, size=1000))
values = np.array([10, 500, 999])
indices = np.searchsorted(arr, values)
print(indices)
This code finds the positions where each value in values should be inserted in the sorted array arr to keep it sorted.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: For each value, a binary search is done on the sorted array.
- How many times: Once per value in the
valuesarray.
Each search takes time that grows slowly as the array size grows, and the total time grows linearly with the number of values searched.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 operations (3 per search x 10 values) |
| 100 | About 700 operations (7 per search x 100 values) |
| 1000 | About 10,000 operations (10 per search x 1000 values) |
Pattern observation: The search per value grows slowly with array size, but total work grows roughly with the number of values searched.
Time Complexity: O(m log n)
This means the time grows linearly with the number of values searched (m) and logarithmically with the size of the sorted array (n).
[X] Wrong: "The search time grows linearly with the size of the array for each value."
[OK] Correct: The search uses binary search, which splits the array repeatedly, so it grows much slower than linear, only logarithmically.
Understanding how search operations scale helps you explain efficient data lookups and insertion points, a useful skill in many data science tasks.
"What if the array was not sorted? How would the time complexity of finding insertion points change?"
Practice
np.searchsorted() function do in NumPy?Solution
Step 1: Understand the purpose of np.searchsorted()
This function finds the position where a new element can be inserted in a sorted array without breaking the order.Step 2: Compare with other options
Options B, C, and D describe different functions: sorting, removing duplicates, and finding max, which are not what searchsorted does.Final Answer:
Finds the index where a value should be inserted to keep the array sorted -> Option DQuick Check:
Insertion index finder = A [OK]
- Confusing searchsorted with sorting functions
- Thinking it removes duplicates
- Assuming it returns values instead of indices
arr using np.searchsorted()?Solution
Step 1: Recall the function signature
The correct syntax is np.searchsorted(array, value), so the array comes first, then the value.Step 2: Check each option
np.searchsorted(arr, 5) matches the correct order. np.searchsorted(5, arr) reverses arguments. arr.searchsorted(5) is invalid because searchsorted is not a method of ndarray. np.searchsorted(arr, value=5) uses a wrong keyword argument.Final Answer:
np.searchsorted(arr, 5) -> Option BQuick Check:
Array first, value second = D [OK]
- Swapping the order of arguments
- Using searchsorted as a method of array
- Using incorrect keyword arguments
import numpy as np arr = np.array([1, 3, 5, 7]) index = np.searchsorted(arr, 4) print(index)
Solution
Step 1: Understand the array and value
The array is [1, 3, 5, 7], and we want to insert 4 while keeping it sorted.Step 2: Find the insertion index
4 fits between 3 (index 1) and 5 (index 2), so the insertion index is 2.Final Answer:
2 -> Option AQuick Check:
Insert 4 between 3 and 5 = 2 [OK]
- Choosing index of smaller element
- Choosing index of larger element
- Confusing zero-based indexing
import numpy as np arr = np.array([2, 4, 6, 8]) index = np.searchsorted(arr, side='left', 5) print(index)
Solution
Step 1: Check function argument order
np.searchsorted expects the array first, then the value, then optional keywords like side.Step 2: Identify the error in argument placement
The code passes side='left' before the value 5, which is incorrect syntax.Final Answer:
The 'side' argument should come after the value argument -> Option AQuick Check:
Keyword args after positional args = A [OK]
- Placing keyword arguments before positional arguments
- Assuming array must be descending
- Thinking scalar values are invalid
arr = np.array([1, 2, 2, 3, 4]), which code snippet will insert the value 2 after all existing 2s using np.searchsorted()?Solution
Step 1: Understand the side parameter
side='right' returns the insertion index after existing equal values; side='left' inserts before.Step 2: Apply to the array
For value 2 in [1, 2, 2, 3, 4], side='right' gives index 3, after the two 2s.Final Answer:
index = np.searchsorted(arr, 2, side='right') -> Option CQuick Check:
Insert after equals = side='right' = C [OK]
- Using side='left' inserts before equal values
- Assuming default side inserts after equals
- Using invalid side='both'
