Altitude limits configuration in Drone Programming - Time & Space Complexity
When setting altitude limits for a drone, the program checks each altitude value to ensure it fits within allowed bounds.
We want to know how the time to check these limits grows as the number of altitude points increases.
Analyze the time complexity of the following code snippet.
function checkAltitudeLimits(altitudes, minLimit, maxLimit) {
for (let i = 0; i < altitudes.length; i++) {
if (altitudes[i] < minLimit || altitudes[i] > maxLimit) {
return false;
}
}
return true;
}
This code checks each altitude in a list to see if it is within the allowed minimum and maximum limits.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the altitude list to check each value.
- How many times: Once for each altitude in the list, until a limit is broken or all are checked.
As the number of altitudes increases, the program checks more values one by one.
| 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 directly with the number of altitudes.
Time Complexity: O(n)
This means the time to check altitude limits grows in a straight line as the number of altitudes increases.
[X] Wrong: "The program checks all altitudes even if one is out of limits."
[OK] Correct: The code stops checking as soon as it finds an altitude outside the limits, so it may run faster than checking all.
Understanding how loops grow with input size helps you explain how your drone code handles many altitude points efficiently.
"What if the altitude list was sorted? How would that affect the time complexity of checking limits?"