RGB LED color mixing in Raspberry Pi - Time & Space Complexity
When mixing colors on an RGB LED, the program changes red, green, and blue values to create new colors.
We want to know how the time to mix colors grows as we try more color combinations.
Analyze the time complexity of the following code snippet.
for red in range(0, 256, 51):
for green in range(0, 256, 51):
for blue in range(0, 256, 51):
set_rgb_led(red, green, blue)
delay(100)
This code cycles through red, green, and blue values in steps of 51 to mix colors on an RGB LED.
- Primary operation: The three nested loops each run through color values.
- How many times: Each loop runs 6 times (0, 51, 102, 153, 204, 255), so total calls are 6 x 6 x 6 = 216.
As the number of color steps increases, the total operations grow quickly because of the three loops.
| Input Size (steps per color) | Approx. Operations |
|---|---|
| 6 | 216 |
| 10 | 1000 |
| 20 | 8000 |
Pattern observation: The total operations grow by the cube of the number of steps because of three nested loops.
Time Complexity: O(n³)
This means if you double the number of color steps, the time to mix colors grows eight times.
[X] Wrong: "The time grows linearly because we just add red, green, and blue loops."
[OK] Correct: The loops are nested, so the total time multiplies, not adds, making the growth much faster.
Understanding how nested loops affect time helps you explain performance in real projects, like controlling hardware or processing images.
"What if we combined the three loops into one loop that sets all colors at once? How would the time complexity change?"