For the worst-case analysis of the code below I think it's O(n^2), however my prof states its O(n), arguing that the maximum amount of operations per element is 2 (one push and one pop).
- Since its an
if-statement, isn't it one or the other? How is it both push and pop? - If it's the "worst-case" why can we not argue first pushing n-1 elements, and then for the very last iteration looping through the entire stack, resulting in O(n^2)?
void foo (int n){
Stack<int> stack = new Stack();
i = 0;
while (i < n) {
int key = random int from 1 to n
if (key is odd)
stack.push(key);
else {
j = 0;
while (j < key and !stack.isEmpty()){
stack.pop();
j = j + 1;
}
i = i + 1;
}
}

