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.
So, in order to expand the other replies, I will try to add a example of such problems to help you understand:
For instance, summing up the elements of 2 vectors can be done in O(M+N), but it can be thought as O(N) (assuming N>M) or O(M) (if M>N).
A simple example of algorithm that is O(m+n)
:
int sum(int[] nArr, int[] mArr) {
int sum = 0;
for(int i : nArr) {
sum += i;
}
for(int i : mArr) {
sum += i;
}
return sum;
}
To compute the sum, you need to go through all elements in nArr
(size n
) and all elements in mArr
(size m
), so the overall complexity is O(m+n)