0
0
Blockchain / Solidityprogramming~5 mins

Flash loans in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Flash loans
O(n)
Understanding Time Complexity

Flash loans are special blockchain transactions that borrow and repay funds instantly within one operation.

We want to understand how the time to execute a flash loan grows as the number of operations inside it increases.

Scenario Under Consideration

Analyze the time complexity of the following flash loan code snippet.


function executeFlashLoan(address token, uint amount) external {
  uint balanceBefore = IERC20(token).balanceOf(address(this));
  lender.flashLoan(amount);
  // Perform multiple operations with the loaned amount
  for (uint i = 0; i < operations.length; i++) {
    operations[i].execute();
  }
  require(IERC20(token).balanceOf(address(this)) >= balanceBefore, "Loan not repaid");
}
    

This code borrows tokens, runs several operations, then repays the loan in one transaction.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop running operations[i].execute() repeatedly.
  • How many times: Once for each operation in the operations list.
How Execution Grows With Input

Each added operation means one more execution step inside the loop.

Input Size (n)Approx. Operations
1010 executions of operations
100100 executions of operations
10001000 executions of operations

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

Final Time Complexity

Time Complexity: O(n)

This means the time to complete the flash loan grows in a straight line as you add more operations.

Common Mistake

[X] Wrong: "The flash loan always takes constant time because it happens in one transaction."

[OK] Correct: Even though it is one transaction, the number of operations inside affects how long the transaction takes to run.

Interview Connect

Understanding how the number of operations affects execution time helps you design efficient smart contracts and shows you can think about costs in blockchain programming.

Self-Check

"What if the operations inside the flash loan called other loops? How would the time complexity change?"