0
0
Raspberry Piprogramming~5 mins

Traffic light simulation in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Traffic light simulation
O(n)
Understanding Time Complexity

When simulating a traffic light, we want to know how the program's running time changes as we add more cycles or lights.

We ask: How does the time to run the simulation grow when we increase the number of light changes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


for cycle in range(num_cycles):
    turn_on_red()
    wait(red_duration)
    turn_on_green()
    wait(green_duration)
    turn_on_yellow()
    wait(yellow_duration)
    
# End of simulation

This code runs a traffic light sequence for a set number of cycles, turning lights on and waiting for their durations.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that repeats the light changes for each cycle.
  • How many times: Exactly num_cycles times, once per cycle.
How Execution Grows With Input

Each cycle runs the same fixed steps of turning lights on and waiting.

Input Size (num_cycles)Approx. Operations
10About 10 cycles of light changes
100About 100 cycles of light changes
1000About 1000 cycles of light changes

Pattern observation: The total work grows directly with the number of cycles; doubling cycles doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the simulation grows in a straight line as you add more cycles.

Common Mistake

[X] Wrong: "The time to run the simulation stays the same no matter how many cycles we have."

[OK] Correct: Each cycle repeats the same steps, so more cycles mean more total time.

Interview Connect

Understanding how loops affect running time helps you explain how programs scale, a key skill in many coding tasks.

Self-Check

"What if we added a nested loop inside each cycle to blink the yellow light multiple times? How would the time complexity change?"