Skip to content
Advertisement

How to justify the time complexity of an algorithm?

I’m relatively new to data structures and could use a bit of help on how you approach justifying an algorithm. I believe the algorithm below to be the time complexity of O(n + m) because you iterate through two different arrays independently. You can also assume the arrays are always sorted.

JavaScript

Advertisement

Answer

Yep, the time complexity is O(n + m).

The worst case scenario could be such that a consists of consecutive odd integers and b – of consecutive even integers (positive) as below:

JavaScript

In this case, both i and j will be incremented up to a.length and b.length. That is exactly a.length + b.length steps or O(n + m), where n = a.length and m = b.length

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement