Search code examples
graphtime-complexitydepth-first-search

Is for each u,v in V loop linear on V?


Knowing that

for each u in V do // O(V)
     // ...

Does this loop:

for each u,v in V do // O(V) or O(V^2)?
     // ...

is linear on V or V^2?


Solution

  • It’s O(V2). More generally, there are Θ(n2) pairs that can be made from a set of n items, and if you iterate over all them it’ll take quadratic time simply listing them out.