Scalar and array broadcasting in NumPy - Time & Space Complexity
We want to understand how the time to run numpy operations changes when using scalars with arrays.
Specifically, how does adding a single number to a big array affect the work done?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.arange(1000)
scalar = 5
result = arr + scalar
This code adds a single number to every element in a numpy array using broadcasting.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding the scalar to each element of the array.
- How many times: Once for each element in the array (1000 times here).
As the array size grows, the number of additions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of elements.
Time Complexity: O(n)
This means the time to add a scalar to an array grows linearly with the array size.
[X] Wrong: "Adding a scalar to an array is instant and does not depend on array size."
[OK] Correct: Even though numpy uses fast operations, it still needs to add the scalar to each element, so time grows with array size.
Understanding how broadcasting affects performance helps you explain efficient numpy code clearly in interviews.
"What if we added two arrays of the same size instead of a scalar and an array? How would the time complexity change?"
Practice
Solution
Step 1: Understand scalar and array addition
A scalar is treated as an array with no dimensions and can be added to each element of the array.Step 2: Apply broadcasting rules
Broadcasting repeats the scalar value to match the shape of the array, adding it element-wise.Final Answer:
The scalar is added to each element of the array. -> Option AQuick Check:
Scalar + array = element-wise addition [OK]
- Thinking scalar is ignored
- Expecting shape mismatch error
- Assuming scalar replaces array
arr?Solution
Step 1: Recall NumPy scalar addition syntax
Adding a scalar to an array is done simply by using the plus operator:arr + scalar.Step 2: Evaluate options
arr + 5 usesarr + 5, which is correct. arr.add(5) is invalid syntax. add(arr, 5) is not a NumPy function. arr + [5] tries to add a list, which changes behavior.Final Answer:
arr + 5 -> Option BQuick Check:
Usearr + scalarfor scalar addition [OK]
- Using method .add() which doesn't exist
- Passing scalar inside a list
- Using non-existent add() function
import numpy as np arr = np.array([1, 2, 3]) result = arr * 3 print(result)
Solution
Step 1: Understand scalar multiplication with array
Multiplying an array by a scalar multiplies each element by that scalar.Step 2: Calculate element-wise multiplication
Each element in[1, 2, 3]is multiplied by 3, resulting in[3, 6, 9].Final Answer:
[3 6 9] -> Option DQuick Check:
Array * scalar = element-wise multiplication [OK]
- Expecting concatenation instead of multiplication
- Thinking output is repeated elements
- Assuming error due to shape mismatch
import numpy as np arr = np.array([1, 2, 3]) scalar = np.array([5]) result = arr + scalar print(result)
Solution
Step 1: Check shapes of arrays
arrshape is (3,),scalarshape is (1,). Broadcasting allows (1,) to expand to (3,).Step 2: Apply broadcasting addition
Each element ofarris added to 5, resulting in[6, 7, 8].Final Answer:
No error; output is [6 7 8] -> Option CQuick Check:
Broadcasting works with (3,) + (1,) arrays [OK]
- Assuming scalar must be a plain number
- Thinking shape mismatch causes error
- Expecting concatenation instead of addition
arr = np.array([[1, 2, 3], [4, 5, 6]]), what is the result of arr + np.array([10, 20, 30])?Solution
Step 1: Analyze shapes for broadcasting
arrshape is (2,3), andnp.array([10, 20, 30])shape is (3,). The second array broadcasts across rows.Step 2: Perform element-wise addition row-wise
Each row ofarradds the vector[10, 20, 30]element-wise, resulting in[[11, 22, 33], [14, 25, 36]].Final Answer:
[[11 22 33] [14 25 36]] -> Option AQuick Check:
Broadcast vector added to each row [OK]
- Expecting error due to different shapes
- Adding vector only to first row
- Confusing addition with concatenation
Ready to prove it?
Pass the test and this pattern moves unknown
