Multiple LED patterns in Raspberry Pi - Time & Space Complexity
When controlling multiple LED patterns on a Raspberry Pi, it is important to understand how the time to run the program changes as we add more LEDs or patterns.
We want to know how the program's running time grows when we increase the number of LEDs or patterns.
Analyze the time complexity of the following code snippet.
for pattern in patterns:
for led in leds:
turn_on(led)
wait(delay)
turn_off(led)
This code runs multiple LED patterns by turning each LED on and off in sequence for each pattern.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops over patterns and LEDs.
- How many times: The inner loop runs once for each LED, repeated for each pattern.
As the number of patterns or LEDs increases, the total operations grow by multiplying these counts.
| Input Size (patterns × LEDs) | Approx. Operations |
|---|---|
| 10 × 5 | 50 |
| 100 × 5 | 500 |
| 100 × 100 | 10,000 |
Pattern observation: Doubling the number of patterns or LEDs roughly doubles the total operations.
Time Complexity: O(p × l)
This means the running time grows proportionally to the number of patterns times the number of LEDs.
[X] Wrong: "The time grows only with the number of LEDs, not patterns."
[OK] Correct: Because the code runs through all LEDs for each pattern, both counts multiply to affect total time.
Understanding how nested loops affect running time helps you explain how your code scales, a key skill in programming and problem solving.
"What if we combined all patterns into one loop instead of nesting? How would the time complexity change?"