0
0
PHPprogramming~5 mins

Strategy pattern in PHP - Time & Space Complexity

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

When using the Strategy pattern, we want to understand how the program's running time changes as we use different strategies.

We ask: how does choosing and running a strategy affect the total work done?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


interface Strategy {
    public function execute(array $data): array;
}

class ConcreteStrategyA implements Strategy {
    public function execute(array $data): array {
        return array_map(fn($x) => $x * 2, $data);
    }
}

class Context {
    private Strategy $strategy;
    public function __construct(Strategy $strategy) {
        $this->strategy = $strategy;
    }
    public function run(array $data): array {
        return $this->strategy->execute($data);
    }
}

This code runs a chosen strategy on an array of data, transforming it according to the strategy's rules.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The array_map function inside the strategy loops over each element of the input array.
  • How many times: It runs once for each item in the input array.
How Execution Grows With Input

As the input array gets bigger, the number of times the strategy's execute method processes elements grows directly with the size.

Input Size (n)Approx. Operations
1010 function calls inside array_map
100100 function calls inside array_map
10001000 function calls inside array_map

Pattern observation: The work grows evenly as the input size grows; doubling input doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the strategy grows in direct proportion to the number of items in the input.

Common Mistake

[X] Wrong: "The Strategy pattern adds extra loops and makes the program slower by a lot."

[OK] Correct: The pattern itself just chooses which code to run; it does not add extra loops beyond what the chosen strategy does.

Interview Connect

Understanding how design patterns affect time helps you explain your choices clearly and shows you think about both design and performance.

Self-Check

"What if the strategy used nested loops inside execute? How would the time complexity change?"