0

When you have an algorithm that may skip a lot of iterations due to a hash table lookup, do you still count the iterations that are exited immediately?

Hypothetical example:

var n = input.length; //eg, [1,4,6,2,0,8]

for (var i = 0; i < n; i++) {
  visited[i] = true;

  for (var j = 0; j < n; j++) {
    if (visited[j] === true) {
      continue;
    }
  }
}

Another example:

function dfs(node) {
  if (visited[node]) {
    return 0;
  }

  visited[node] = true;

  var edges = edges[node];

  for (var i = 0; i < edges.length; i++) {
    dfs(edges[i]);
  }
}

//dfs(graph_that_has_cycles);
Raphael
  • 73,212
  • 30
  • 182
  • 400
tau
  • 135
  • 3

1 Answers1

1

If the average number of times the inner loop is $O(f(n))$ then the total complexity is $O(n \times f(n))$.

Finding that average can be tricky when the condition is not trivial. however assuming that it never drops a loop will give you a worst case. This worst case will also be valid when the amount of inner loops skipped is a constant factor.

However in the first example the loop can be simplified to

for (var i = 0; i < n; i++) {
  visited[i] = true;

  for (var j = i+1; j < n; j++) {
      //...
  }
}

This is $O(n^2)$. Because $\Sigma_{i=0}^n i = \frac{n(n+1)}{2} = O(n^2)$

ratchet freak
  • 4,696
  • 1
  • 18
  • 15