0
0
Pythonprogramming~5 mins

Multiple parameters in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Multiple parameters
O(n * m)
Understanding Time Complexity

When a function takes more than one input, we want to know how its running time changes as these inputs grow.

We ask: How does the work increase when each input gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def combine_lists(list1, list2):
    result = []
    for item1 in list1:
        for item2 in list2:
            result.append((item1, item2))
    return result

This function pairs every item from the first list with every item from the second list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Nested loops over both lists.
  • How many times: Outer loop runs once per item in list1; inner loop runs once per item in list2 for each outer loop.
How Execution Grows With Input

Each item in the first list pairs with every item in the second list, so work grows with both sizes multiplied.

Input Size (list1, list2)Approx. Operations
(10, 10)100
(100, 100)10,000
(1000, 1000)1,000,000

Pattern observation: Doubling both lists multiplies work by four; work grows fast as both inputs grow.

Final Time Complexity

Time Complexity: O(n * m)

This means the time grows by multiplying the sizes of both inputs together.

Common Mistake

[X] Wrong: "The time depends only on the bigger list size."

[OK] Correct: Because the function pairs every item from one list with every item from the other, both sizes matter equally.

Interview Connect

Understanding how multiple inputs affect time helps you explain your code clearly and shows you can think about real problems with several factors.

Self-Check

"What if we changed the inner loop to only run half the size of list2? How would the time complexity change?"