Barometer for altitude in Drone Programming - Time & Space Complexity
When using a barometer to measure altitude in a drone, it's important to understand how the time to process sensor data grows as we collect more readings.
We want to know how the program's work changes when the number of altitude readings increases.
Analyze the time complexity of the following code snippet.
# Read altitude values from barometer sensor
altitudes = []
for i in range(n):
altitude = read_barometer()
altitudes.append(altitude)
# Calculate average altitude
sum_altitude = 0
for altitude in altitudes:
sum_altitude += altitude
average = sum_altitude / n
This code reads n altitude values from the barometer and then calculates their average.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two loops: one to read and store altitude values, one to sum them.
- How many times: Each loop runs n times, where n is the number of readings.
As the number of altitude readings increases, the total work grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (10 reads + 10 sums) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: Doubling the number of readings roughly doubles the total operations.
Time Complexity: O(n)
This means the time to process altitude readings grows linearly with the number of readings.
[X] Wrong: "Reading more altitude values won't affect the time much because each read is fast."
[OK] Correct: Even if each read is quick, doing many reads adds up, so total time grows with the number of readings.
Understanding how sensor data processing time grows helps you design efficient drone programs and shows you can think about performance in real tasks.
"What if we calculated the average altitude while reading each value instead of after collecting all readings? How would the time complexity change?"