Range finder for terrain following in Drone Programming - Time & Space Complexity
When programming a drone to follow terrain using a range finder, it's important to understand how the time it takes to process sensor data grows as the drone moves.
We want to know how the program's work changes as it reads more distance points.
Analyze the time complexity of the following code snippet.
function followTerrain(distances) {
for (let i = 0; i < distances.length; i++) {
let distance = distances[i];
adjustAltitude(distance);
}
}
function adjustAltitude(distance) {
// Adjust drone altitude based on distance
}
This code reads a list of distance measurements from the range finder and adjusts the drone's altitude for each measurement.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the distances array to read each distance.
- How many times: Once for each distance measurement in the input list.
As the number of distance points increases, the program processes each one in order.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 adjustments |
| 100 | 100 adjustments |
| 1000 | 1000 adjustments |
Pattern observation: The work grows directly with the number of distance points; doubling points doubles work.
Time Complexity: O(n)
This means the time to adjust altitude grows in a straight line with the number of distance measurements.
[X] Wrong: "The program runs in constant time because it just adjusts altitude once."
[OK] Correct: The program adjusts altitude for every distance point, so more points mean more work, not just one adjustment.
Understanding how sensor data processing scales helps you write efficient drone control code and shows you can think about performance in real tasks.
"What if the adjustAltitude function itself had a loop over the input? How would the time complexity change?"