I\'m working through some practice problems where I\'m given a target time complexity and space complexity. One of them gives a target time complexity of O(N+M). I\'m having som
Quick and simple example of an O(n + m) algorithm:
for (i = 0; i < n; i++)
{
// do something but don't loop or invoke recursive functions
// only constant O(c) complexity is allowed: a simple series of commands
}
for (i = 0; i < m; i++)
{
// idem
}
Complexity is commutative when added (O(n + m) == O(m + n)) this means you may invert the two for()
without affecting complexity. Obviously, on an algorithmic level the inverted one MAY not be equivalent to the straight one.
As an additional help, here is an example of O(n * m) algorithm:
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
// do something but don't loop or invoke recursive functions
// only constant O(c) complexity is allowed: a simple series of commands
}
}
Again, you may invert inside with outside loop without affecting complexity (O(n * m) == O(m * n)). The same obvious considerations apply.
The limitation on what you may put into the for()
bodies is because the big-o notation constraints the upper bound. If it were a lower bound (little-o notation) you may have put more complex stuff in, but it could never get less than that.