0
0
Raspberry Piprogramming~5 mins

LED toggle with button in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: LED toggle with button
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run the LED toggle program changes as we press the button more times.

How does the program's work grow when the button is pressed repeatedly?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
LED_PIN = 18
BUTTON_PIN = 23

GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

led_state = False

while True:
    button_state = GPIO.input(BUTTON_PIN)
    if button_state == GPIO.LOW:
        led_state = not led_state
        GPIO.output(LED_PIN, led_state)
        time.sleep(0.3)  # debounce delay

This code waits for a button press and toggles an LED on or off each time the button is pressed.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop that continuously checks the button state.
  • How many times: It runs forever, repeating as many times as the program runs.
How Execution Grows With Input

Each time the button is pressed, the program does a small fixed amount of work to toggle the LED.

Input Size (button presses)Approx. Operations
10About 10 toggles and checks
100About 100 toggles and checks
1000About 1000 toggles and checks

Pattern observation: The work grows directly with the number of button presses, one toggle per press.

Final Time Complexity

Time Complexity: O(n)

This means the program's work grows in a straight line with the number of button presses.

Common Mistake

[X] Wrong: "The program does a lot more work each time the button is pressed because it loops forever."

[OK] Correct: The loop runs continuously, but the main work only happens when the button is pressed, so work grows only with presses, not time running.

Interview Connect

Understanding how repeated actions affect program work helps you explain how your code behaves in real devices, showing you can think about efficiency clearly.

Self-Check

"What if we added a second button to toggle the LED off only? How would the time complexity change?"