I am reading about the Rabin-Karp algorithm on Wikipedia and the time complexity mentioned in there is O(n+m). Now, from my understanding, m is necessarily between 0 and n, so in the best case the complexity is O(n) and in the worst case it is also O(2n)=O(n), so why isn't it just O(n)?
-
1I think this is just to show that there is linear dependency also between complexity of algorithm and `m` – Ivan Jan 24 '19 at 06:43
3 Answers
Basically, Robin-Karp expresses it's asymptotic notation as O(m+n)
as a means to express the fact that it takes linear time relative to m+n
and not just n
. Essentially, the variables, m
and n
, have to mean something whenever you use asymptotic notation. For the case of the Robin-Karp algorithm, n
represents the length of the text, and m
represents the combined length of both the text and the pattern. Note that O(2n)
means the same thing as O(n)
, because O(2n)
is still a linear function of just n
. However, in the case of Robin-Karp, m+n
isn't really a function of just n
. Rather, it's a function of both m
and n
, which are two independent variables. As such, O(m+n)
doesn't mean the same thing as O(n)
in the same way that O(2n)
equates to O(n)
.
I hope that makes sense. :-P

- 10,049
- 8
- 47
- 68
m
and n
measure different dimensions of the input data. Text of length n
and patterns of length m
is not the same as text of length 2n
and patterns of length 0
.
O(m+n)
tells us that the complexity is proportional to both the length of the text and the length of the patterns.

- 3,677
- 1
- 14
- 24
There are some scenarios where saying complexity in form of O(n+m)
is suitable than just saying O(max(m,n))
.
Scenario:
Consider BFS(Breadth First Search) or DFS(Depth First Search) as Scenario.
It will be more intuitive and will convey more information to say that the complexity is O(E+V)
than max{E,V}
. The former is in Sync with actual algorithmic description.

- 5,567
- 5
- 33
- 55