0
0
Blockchain / Solidityprogramming~5 mins

Reentrancy guard pattern in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Reentrancy guard pattern
O(n)
Understanding Time Complexity

When using the reentrancy guard pattern, we want to know how the cost of checking and updating the guard changes as the number of calls grows.

We ask: How does the time spent grow when many function calls happen?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


bool locked = false;

function withdraw() public {
  require(!locked, "No reentrancy");
  locked = true;
  // send funds
  locked = false;
}
    

This code prevents a function from being called again before the first call finishes, protecting against repeated entry.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking and setting the locked flag on each call.
  • How many times: Once per function call, no loops or recursion inside.
How Execution Grows With Input

Each call does a simple check and update, so the work grows directly with the number of calls.

Input Size (n)Approx. Operations
1010 checks and updates
100100 checks and updates
10001000 checks and updates

Pattern observation: The time grows steadily as calls increase, with no extra loops or nested work.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the number of calls, as each call does a fixed amount of work.

Common Mistake

[X] Wrong: "The reentrancy guard adds extra loops or slows down calls exponentially."

[OK] Correct: The guard only checks and sets a simple flag once per call, so it does not add loops or nested work.

Interview Connect

Understanding how simple checks like the reentrancy guard scale helps you explain smart contract safety clearly and confidently.

Self-Check

"What if the withdraw function included a loop over a list of recipients? How would the time complexity change?"