Battery failsafe in Drone Programming - Time & Space Complexity
We want to understand how the time it takes to check the battery status grows as the number of checks increases.
How does the program's running time change when it repeatedly monitors the battery?
Analyze the time complexity of the following code snippet.
function batteryFailsafe(batteryLevels) {
for (let level of batteryLevels) {
if (level < 20) {
triggerFailsafe()
break
}
}
}
function triggerFailsafe() {
// Actions to safely land the drone
}
This code checks each battery level in a list and triggers a failsafe if any level is below 20%.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the batteryLevels list.
- How many times: Up to once for each battery level until a low level is found or the list ends.
As the number of battery levels increases, the program may check more items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows roughly in direct proportion to the number of battery levels.
Time Complexity: O(n)
This means the time to check battery levels grows linearly with the number of levels to check.
[X] Wrong: "The failsafe check always takes the same time no matter how many battery levels there are."
[OK] Correct: The program may need to check many battery levels before finding a low one or finishing the list, so time grows with input size.
Understanding how loops affect time helps you explain how your code handles real-world data sizes efficiently.
"What if the code checked battery levels in parallel instead of one by one? How would the time complexity change?"