0
0
Matplotlibdata~5 mins

Waterfall chart pattern in Matplotlib - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Waterfall chart pattern
O(n)
Understanding Time Complexity

We want to understand how the time to draw a waterfall chart changes as the data size grows.

How does the number of steps affect the work matplotlib does to build the chart?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


import matplotlib.pyplot as plt

values = [100, -30, 20, -10, 40]

cumulative = [0]
for v in values:
    cumulative.append(cumulative[-1] + v)

plt.bar(range(len(values)), values, bottom=cumulative[:-1])
plt.show()
    

This code builds a simple waterfall chart by stacking bars based on cumulative sums.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Loop over the list of values to compute cumulative sums and draw bars.
  • How many times: Once for each value in the input list.
How Execution Grows With Input

Each new data point adds one more bar and one more cumulative sum calculation.

Input Size (n)Approx. Operations
10About 10 cumulative sums and 10 bars drawn
100About 100 cumulative sums and 100 bars drawn
1000About 1000 cumulative sums and 1000 bars drawn

Pattern observation: The work grows directly with the number of data points.

Final Time Complexity

Time Complexity: O(n)

This means the time to create the waterfall chart grows in a straight line as the data size increases.

Common Mistake

[X] Wrong: "Drawing a waterfall chart takes the same time no matter how many bars there are."

[OK] Correct: Each bar requires calculations and drawing steps, so more bars mean more work.

Interview Connect

Understanding how chart drawing time grows helps you explain performance in data visualization tasks clearly and confidently.

Self-Check

What if we added nested loops to compare each bar with every other bar? How would the time complexity change?