Time complexity of simultaneous iteration

86 Views Asked by At

I'm struggling to understand what will be the time complexity of simultaneous iteration. If we have a function that takes two arrays and iterates over them sequentially it's obvious:

def process(a: list, b: list):
    for i in range(len(a)):
      a[i]
    for i in range(len(b)):
      b[i]

We have O(a.length + b.length)

But if we have a knowing that the length of lists are the same and we do simultaneous iteration:

def process(a: list, b: list):
    for i in range(len(a)):
      a[i]
      b[i]

Does it mean we have O(a.length) ?

1

There are 1 best solutions below

4
pochopsp On BEST ANSWER

Given that a and b have the same length, say N, you can say for sure that BOTH your examples will run in O(N).

If you have instead the precondition of

  • len(a) = N
  • len(b) = M

Then, your first algorithm will run in O(N+M) and your second one will run in O(N) since you're limiting the iteration on the length of a.

It's all a matter of preconditions and constraints on the input in this case