0
0
Raspberry Piprogramming~5 mins

LED brightness control in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: LED brightness control
O(n)
Understanding Time Complexity

When controlling LED brightness on a Raspberry Pi, we often adjust values repeatedly in a loop.

We want to understand how the time it takes grows as we change the number of brightness steps.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
LED_PIN = 18
GPIO.setup(LED_PIN, GPIO.OUT)
pwm = GPIO.PWM(LED_PIN, 1000)
pwm.start(0)

for brightness in range(0, 101):
    pwm.ChangeDutyCycle(brightness)
    time.sleep(0.01)

pwm.stop()
GPIO.cleanup()

This code gradually increases LED brightness from 0% to 100% in steps, pausing briefly at each step.

Identify Repeating Operations
  • Primary operation: The for-loop that changes brightness 101 times.
  • How many times: Once for each brightness level from 0 to 100.
How Execution Grows With Input

As the number of brightness steps increases, the loop runs more times, increasing total operations.

Input Size (n)Approx. Operations
1010 brightness changes
100100 brightness changes
10001000 brightness changes

Pattern observation: The total work grows directly with the number of brightness steps.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete grows in a straight line as you increase brightness steps.

Common Mistake

[X] Wrong: "Changing brightness a few more times won't affect the total time much."

[OK] Correct: Each brightness change takes time, so more steps add up and increase total time linearly.

Interview Connect

Understanding how loops affect time helps you explain how your code scales, a key skill in many programming tasks.

Self-Check

"What if we changed the loop to increase brightness in steps of 5 instead of 1? How would the time complexity change?"