We looked at the running time of the following method:

void removeAll( E item )        // removes all occurrences of the given item
{
    while ( remove(item) ) {    // remove a single occurrence, try again
        ;
    }
}

Our hunch was that the running time of removeAll is O(n^2):

We tried to find a configuration that achieves the O(n^2) running time. (We will use big-O below even when big-Ω or big-Θ are more appropriate.)

We used a couple of estimates (no need to be precise, just convincing):

In all cases we will try to remove 8, the rest will be 7 (both arbitrarily chosen).

Single 8 at the end

Suppose the list is: 7→7→7→...7→8:

cyclework detailsworklist
7→7→7→...7→8
1.
  • inspects n-1 boxes with 7s: 3(n-1) units work
  • deletes the last 8: 6 units of work
3(n-1)+6 7→7→7→...7
2.
  • inspects n-1 boxes with 7s: 3(n-1) units work
  • done, no 8 found
3(n-1) 7→7→7→...7
Total work: 3(n-1) + 6 + 3(n-1) = 3n, so O(n). Did not reach our goal.

Only 8s in the list

Suppose the list is: 8→8→8→...8→8:

cyclework detailsworklist
8→8→8→...8→8
1.
  • deletes first 8 right away: 6 units of work
6 8→8→...8→8
2.
  • deletes first 8 right away: 6 units of work
6 8→...8→8
...
n-1.
  • deletes first 8 right away: 6 units of work
6 8
n.
  • deletes first 8 right away: 6 units of work
6 empty
last.
  • done, no 8 found
2 empty
Total work: 6n + 2, so O(n). Did not reach our goal.

1st half only 7s, 2nd half only 8s

Suppose the list is: 7→7→7→...→7→8→8→8...→8:

cyclework detailsworklist
7→7→7→...→7→8→8→8...→8
1.
  • inspects n/2 boxes with 7s: 3(n/2) units work
  • deletes first 8: 6 units of work
3(n/2)+6 7→7→7→...→7→8→8...→8
2.
  • inspects n/2 boxes with 7s: 3(n/2) units work
  • deletes first 8: 6 units of work
3(n/2)+6 7→7→7→...→7→8...→8
...
n/2.
  • inspects n/2 boxes with 7s: 3(n/2) units work
  • deletes first 8: 6 units of work
3(n/2)+6 7→7→7→...→7
last.
  • done, no 8 found
2 empty
Total work: n/2*(3(n/2) + 6) + 2 = 3/4n^2 + 3n + 2, so O(n^2). Reached the goal.

1st half only 8s, 2nd half only 7s

Suppose the list is: 8→8→8→...→8→7→7→7...→7:

cyclework detailsworklist
8→8→8→...→8→7→7→7...→7
1.
  • ?
? ?
2.
  • ?
? ?
...
?
  • ?
? ?
last.
  • ?
? ?
Total work: ?

Alternating 7s and 8s (half of each)

cyclework detailsworklist
7→8→7→8→7→8...→7→8
1.
  • ?
? ?
2.
  • ?
? ?
...
?
  • ?
? ?
last.
  • ?
? ?
Total work: ?