Automated plant watering system in Raspberry Pi - Time & Space Complexity
When building an automated plant watering system, it is important to understand how the time it takes to check and water plants grows as you add more plants.
We want to know how the program's work changes when the number of plants increases.
Analyze the time complexity of the following code snippet.
plants = ["plant1", "plant2", "plant3", "plant4"]
for plant in plants:
moisture = read_moisture_sensor(plant)
if moisture < threshold:
water_plant(plant)
This code checks each plant's soil moisture and waters it if the soil is dry.
- Primary operation: Looping through each plant in the list.
- How many times: Once for every plant in the list.
As the number of plants increases, the program checks each one once, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 moisture checks and possible watering actions |
| 100 | About 100 moisture checks and possible watering actions |
| 1000 | About 1000 moisture checks and possible watering actions |
Pattern observation: The work grows directly in proportion to the number of plants.
Time Complexity: O(n)
This means the time to check and water plants grows in a straight line as you add more plants.
[X] Wrong: "The program only takes a fixed amount of time no matter how many plants there are."
[OK] Correct: Because the program must check each plant, more plants mean more work and more time.
Understanding how your program scales with more plants shows you can think about efficiency, which is a useful skill for many real-world projects.
"What if we added a nested loop to check each plant multiple times per cycle? How would the time complexity change?"