ELABORATED and SIMPLIFIED-----------------------------------------------------------
The question I was asked in the coding interview required me to implement a stack. The skeleton of the class was provided with function definitions given as well. However, there was no logic inside the definitions.
class myStack {
f1(args) {//no logic I have to code it}
f2(args) {//no logic I have to code it}
........
};
These functions had to be implemented with run-time O(1). I could get simpler ones done, however, there was an increment function which I could not. (Look at comment in code section below)
void incre(int number, int increment) {
/* In this function, implement logic to implement increment of "number"
elements from the bottom of the stack by "increment".
incre(3, 5) -> means increment 3 elements from bottom of stack. Increment each by 5
*/
}
It was this function that posed a challenge as I had to do the operation in amortized O(1) time.
vec = 1 2 3 4 5
+ 1 1 1 1 // how to in O(1) time instead of loop?
vec = 2 3 4 5 5
The stack was implemented as a vector data structure inside the class by me. Since I implemented the function as a loop, I probably failed test cases.
So how to do it in O(1) time? Any data structure that could help?